首页 > 解决方案 > 完成后(或加载数组中的项目后)如何运行函数?

问题描述

我正在尝试为聊天设置动画。我有一个功能,每次按下输入字段/按钮时,一次加载一条蓝色消息。现在,我希望在最后一条蓝色消息出现后一次自动出现一条灰色消息。我现在拥有的 JS 代码让它们在第一条蓝色消息之后自动出现(延迟一秒)。

HTML

        <div class="messages">
                    <div class="blue invisible" id="msg1">Hi! I'm looking for an old friend. She attended Martin Grove a few years ago.</div>
                    <div class="blue invisible" id="msg2">Her name is Sam. *insert pic of Sam and MC*</div>
                    <div class="blue invisible" id="msg3">Did you know her or her last name by any chance? </div>
                    <div class="grey" id="msg4" style="display: none;">Hello there!</div>
                    <div class="grey" id="msg5" style="display: none;">Unfortunately, I did not have the pleasure of teaching Sam. Her last name and whereabouts are a mystery to me as well. </div> 
    </div>
    
                <div class="input" id="chat-button" onClick="showMessage()">
                    
                </div> 

CSS

.invisible {
    display: none;
}

JS

const myHTMLCollection = document.getElementsByClassName("invisible");
const HTMLElementsArr = [...myHTMLCollection];

function blueMessage() {
    if (HTMLElementsArr.length > 0) {
        HTMLElementsArr.shift().classList.remove('invisible');
        greyMessage();
    }
}


function greyMessage() {
    setTimeout("show_second()", 1000);
}

function show_second() {
    document.getElementById("msg4").style.display = "block";
    setTimeout("show_third()", 1000);
}

function show_third() {
    document.getElementById("msg5").style.display = "block";
}

动画聊天

标签: javascriptjqueryarrayscallback

解决方案


greyMessage()仅在数组为空时调用,因此替换:

greyMessage()

和:

if (!HTMLElementsArr.length) greyMessage();

作为旁注,将字符串作为回调参数传递给setTimeout. 传递函数对象(不带括号)。因此,例如,替换:

setTimeout("show_second()", 1000);

和:

setTimeout(show_second, 1000);

推荐阅读