javascript - 完成后(或加载数组中的项目后)如何运行函数?
问题描述
我正在尝试为聊天设置动画。我有一个功能,每次按下输入字段/按钮时,一次加载一条蓝色消息。现在,我希望在最后一条蓝色消息出现后一次自动出现一条灰色消息。我现在拥有的 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";
}
解决方案
greyMessage()
仅在数组为空时调用,因此替换:
greyMessage()
和:
if (!HTMLElementsArr.length) greyMessage();
作为旁注,将字符串作为回调参数传递给setTimeout
. 传递函数对象(不带括号)。因此,例如,替换:
setTimeout("show_second()", 1000);
和:
setTimeout(show_second, 1000);
推荐阅读
- java - java if 语句如何处理空值?
- python-3.x - 使用 Python 3 的 Google App Engine:混合标准和灵活的 Websockets
- c++ - 使用 std::ifstream::read 读取大型二进制块 > INT32_MAX
- python - TypeError:“str”对象不是迭代器
- elasticsearch - Elasticsearch 问题,我应该在 2 个不同的索引上有重复的数据吗?不知道如何设置数据
- swift - Xcode 和 git 用于解析 swift 包的区别
- azure - Automatic Pr's in Azure Repos
- ios - iOS:如何在按钮中显示阴影图像?
- c - 在 for 循环中向数组添加元素
- docker - Docker 实现中的微服务