繁体   English   中英

创建新消息/元素时如何自动滚动到div的底部

[英]How to automatically scroll to the bottom of div when a new message / element is created

当用户发布新消息时,我想滚动到页面底部,当发布新消息时,它会创建一个看起来像这样的元素(代码是jinja2格式,但这并不重要,基本上我就是这样做的是设置消息的样式,并从我的数据库中获取以前的消息(如果有的话),并使用 for 循环显示它们),

<div class="container">
    <div class="jumbotron" id="messages">
        <div class="message_holder">
            {% if previous_chat %}
            {% for i in previous_chat %}
            <div style="margin-bottom: 10px; padding: 15px;" class="msg">
                <span>
                    <img src="{{ url_for('static', filename='images/nyan.gif') }}" height="32" width="32"
                        style="border-radius: 50%;">
                    <b style="margin-left: 8px; font-size: 18px; vertical-align: middle;">{{ i.user.username }}</b>
                </span>
                <code style="margin-left: 5px; display: none;"
                    class="time-posted">{{ i.created_date.strftime("%d %B %Y %X") }} GMT</code><br>
                <span style="margin-left: 40px;">{{ i.message }}</></span>
            </div>
            {% endfor %}
            {% endif %}
        </div>
    </div>
</div>

这是我当前的 javascript 这样做,但它只适用于页面刷新,而不是在创建新元素时(我尝试使用 while 循环连续 go 到消息的底部,但它只是挂起网站)

$("#messages").ready(function () {
  $("#messages").scrollTop($("#messages")[0].scrollHeight);
});

这是消息 jumbotron 的 CSS

#messages {
  overflow-y: scroll;
  margin-top: 3rem;
  margin-bottom: 1rem;
  height: 75vh;
  border: 2px solid gray;
  padding: 25px;
  border-radius: 5px;
}

提前致谢!

这是您的解决方案,这是一种蛮力,但最好您可以在没有任何外部库的情况下完成

function updateScroll() {
  var element = document.getElementById("messages");
  element.scrollTop = element.scrollHeight;
}
setInterval(updateScroll, 100); // Update every 100 ms (almost unnoticed)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM