首页 > 解决方案 > 如何在消息出现时自动滚动聊天框?

问题描述

我正在为聊天设置动画。每次按下输入字段/按钮时,第一个函数一个接一个地加载蓝色消息。然后,在最后一条蓝色消息出现后,第二个功能会自动一次显示一条灰色消息。但现在我希望聊天框在灰色消息出现时自动向下滚动

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

解决方案


推荐阅读