【问题标题】:scroll to the bottom of the content if some content has been added to the `div`如果某些内容已添加到“div”,则滚动到内容的底部
【发布时间】:2021-01-31 14:42:53
【问题描述】:

我有一个 div,如果 div 中添加了一些内容,我希望它滚动到内容的底部。

这个 div 有动态添加的内容,需要一直向下滚动。现在,如果用户决定向上滚动,那么如果添加了新内容,无论滚动条的当前位置如何,我都希望它跳回底部,它不应该等待用户再次向下滚动,比如在大多数聊天应用程序中。

我将如何创建它?我已经尝试了下面的代码,但它似乎没有工作。

let tempCounter = 0;
var msgdiv = document.getElementById("messages");

function addContent() {
  msgdiv.innerHTML +=
    "Long long content " + tempCounter++ + "!<br/>";

/***
  msgdiv.scrollTop = msgdiv.scrollHeight - msgdiv.clientHeight;
  ***/
  
  msgdiv.scrollTop = msgdiv.scrollHeight;


}

setInterval(function() {
  addContent();

}, 500)
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.h-100 {
  height: 100%;
}

.flex-column {
  flex-direction: column;
}

.d-flex {
  display: flex;
}

.mh-100 {
  max-height: 100%;
}

.chat-messages {
  flex: 1;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column-reverse;
}

.bg-white {
  background-color: #fff;
}

.chat-messages-text {
  display: flex;
  justify-content: flex-start;
}
<div class="d-flex flex-column h-100">
  <div class="chat-messages bg-white">
    <div class="chat-messages-text" id="messages">
    </div>
  </div>
  <div class="chat-input bg-warning ">
    <textarea class="form-control" id="inputs" rows="3"></textarea>
    <button type="button" onclick="addContent()" class="btn btn-primary mb-2"> Send Message </button>
  </div>
</div>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    如果你使用

    msgdiv.scrollIntoView(false);
    

    它将滚动视图保持在元素的底部。 (true 会将其保持在顶部。)

    【讨论】:

    • 这似乎工作..但是这个解决方案没有任何警告吗?只是问你知道吗?
    • @aakashbahyal 我也认为有一些警告,特别是 Safari 不支持它,但我已经在 Safari IOS 上进行了测试,它是可以的。我将在其他浏览器上进行测试。我认为 IE 不支持它。如果您发现问题,请告诉我,我会更新答案。
    【解决方案2】:

    您可以使用Mutation Observer API 来检测您的 div 的变化,然后您可以触发滚动到底部

    【讨论】:

    • 这是一个有趣的函数,但在这种情况下,问题是如何进行滚动,代码已经知道何时添加了新内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2014-10-01
    • 2021-04-29
    • 2022-01-07
    • 2021-10-17
    相关资源
    最近更新 更多