当新内容出现在溢出底部时,使用 SO 答案保持滚动到底部的问题 div

Problems using SO answer of staying scrolled to the bottom when new content appears at the bottom of the overflow div

我一直在使用 this question 上的前两个答案,但无法正常工作。

这是我的代码

$(function(){

// Now let's load our messages
function load_messages(){
    $( "#chatscreen" ).append( "<br>Test" );
}

var out = document.getElementById("chatscreen");
var c = 0;
var add = setInterval(function() {
    // allow 1px inaccuracy by adding 1
    var isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1;
    //console.log(out.scrollHeight - out.clientHeight,  out.scrollTop + 1);
    var newElement = document.createElement("div");

    newElement.innerHTML = c++;
    out.appendChild(newElement);

    // scroll to bottom if isScrolledToBotto
    if(isScrolledToBottom) {out.scrollTop = out.scrollHeight - out.clientHeight; }
}, 1000);

setInterval(load_messages,300); // change to 300 to show the latest message you sent after pressing enter // comment this line and it works, uncomment and it fails
                                // leaving it on 1000 shows the second to last message
setInterval(updateScroll,30);
});

load_messages 函数的目的是将聊天室中已发布的新消息添加到 #chatscreen div 每 300 毫秒。

load_messages 向 div 添加新消息时,滚动条不会停留在 div 的底部。

本回答已移至上述问题。 See this answer.