javascript - 如何在消息出现时自动滚动聊天框?
问题描述
我正在为聊天设置动画。每次按下输入字段/按钮时,第一个函数一个接一个地加载蓝色消息。然后,在最后一条蓝色消息出现后,第二个功能会自动一次显示一条灰色消息。但现在我希望聊天框在灰色消息出现时自动向下滚动。
const myHTMLCollection = document.getElementsByClassName("invisible");
const HTMLElementsArr = [...myHTMLCollection];
function blueMessage() {
if (HTMLElementsArr.length > 0) {
HTMLElementsArr.shift().classList.remove("invisible");
}
if (!HTMLElementsArr.length) {
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";
setTimeout(show_fourth, 1000);
}
function show_fourth() {
document.getElementById("msg6").style.display = "block";
setTimeout(show_fifth, 1000);
}
function show_fifth() {
document.getElementById("msg7").style.display = "block";
setTimeout(show_sixth, 1000);
}
function show_sixth() {
document.getElementById("msg8").style.display = "block";
setTimeout(show_seventh, 1000);
}
function show_seventh() {
document.getElementById("msg9").style.display = "block";
}
.messages {
height: 500px;
overflow-y: scroll;
}
.invisible {
display: none;
}
<div class="messages" id="chat-window">
<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 class="grey" id="msg6" style="display: none">
However, I do know she was in the photography club. I always saw her carrying a camera, always taking pictures.
</div>
<div class="grey" id="msg7" style="display: none">
In fact, I believe she won a contest for one of them.
</div>
<div class="grey" id="msg8" style="display: none">
She’s a super talented girl!
</div>
<div class="grey" id="msg9" style="display: none">
Best of luck on your search. I hope you two are reunited soon!
</div>
</div>
<div class="input" id="chat-button" onClick="blueMessage()"></div>
解决方案
推荐阅读
- javascript - Dropzone以编程方式在div内不起作用
- c# - Xrm.Sdk Linq 与 Joins 和动态 where
- mysql - 如何连接两个 MySQL 表并检查第二个表中的行状态
- restheart - 无法启动 RestHeart Security
- django - 如何在基于类的视图中过滤多对多查询?
- javascript - 将 HTML 字符串转换为 JSON 对象
- solr - Solr 嵌套文档未正确设置
- sqlite - 从 Sqlite 数据库中删除密码
- python - 空类的实例和对象的实例之间的区别?
- python - ModuleNotFoundError:没有名为“假设”的模块