【问题标题】:Chat box scroll down new messages聊天框向下滚动新消息
【发布时间】:2020-07-22 16:26:01
【问题描述】:

我希望当用户打开该聊天或写任何消息时,滚动条向下查看最新消息。我找到了以下我想用来完成任务的答案。 https://stackoverflow.com/a/21067431/12051965

问题是它对滚动条没有任何影响,它仍然在聊天框的顶部,如果有人能告诉我我做错了什么,我将不胜感激。

let chat = document.getElementById("chat-messages-main-div-id");
window.onload = toBottom;

function toBottom() { 
  const isScrolledToBottom = chat.scrollHeight - chat.clientHeight <= chat.scrollTop + 1;
  if (isScrolledToBottom) {
    chat.scrollTop = chat.scrollHeight - chat.clientHeight;
  }
}
.chat-messages-main-div {
  width: 100%;
  height: inherit;
  overflow: overlay;
  overflow-y: scroll;
  display: flex;
  flex-direction: column;
  padding-left: 2%;
  padding-right: 2%;
  box-sizing: border-box;
  padding-bottom: 15px;
}
<div id="chat-messages-main-div-id" class="chat-messages-main-div" onload="toBottom">
   ....
</div>

【问题讨论】:

  • 我建议在所有消息之后添加一个底部 div,并使用类似scrollIntoView

标签: javascript html css


【解决方案1】:

您的代码 sn-p 有两个问题,第一个来自高度:inherited,这会使您的 div 与父元素一起增长,因此您看到的滚动条是父节点(如果是第一个固定高度的父节点,则任何或窗口对象)滚动条而不是聊天滚动条,div或其父级必须限制其高度才能工作,toBottom函数中的比较也应该是> =而不是

function toBottom() { 
  chat.scroll(0, chat.scrollHeight)
}

【讨论】:

  • 如果div 的父级有height: 470px; 并且仍然不起作用怎么办?这就是您所说的父母的固定高度吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
  • 1970-01-01
  • 2015-07-19
  • 2022-01-26
相关资源
最近更新 更多