【问题标题】:How to automatically scroll to the bottom of div when a new message / element is created创建新消息/元素时如何自动滚动到div的底部
【发布时间】:2022-01-17 11:02:14
【问题描述】:

当用户发布新消息时,我想滚动到页面底部,当发布新消息时,它会创建一个看起来像这样的元素(代码是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 循环不断转到消息的底部,但它只是挂起网站)

$("#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;
}

提前致谢!

【问题讨论】:

    标签: javascript html jquery scroll


    【解决方案1】:

    这是你的解决方案,它是一种蛮力,但最好你可以在没有任何外部库的情况下做到这一点

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

    【讨论】:

    • 这可行,但延迟仍然存在,但我可以解决这个问题,谢谢?
    猜你喜欢
    • 2021-02-22
    • 2018-09-15
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多