我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。

我将所有内容都包装在这个div中:

#scroll {
    height:400px;
    overflow:scroll;
}

是否有一种方法来保持它滚动到底部默认使用JS?

有办法保持它滚动到ajax请求后的底部吗?


当前回答

以下是我在我的网站上使用的:

var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;

其他回答

你可以像这样使用HTML DOM scrollIntoView方法:

var element = document.getElementById("scroll");
element.scrollIntoView();

像你一样,我正在构建一个聊天应用程序,并希望最近的消息滚动到视图中。这最终对我很有效:

//get the div that contains all the messages
let div = document.getElementById('message-container');

//make the last element (a message) to scroll into view, smoothly!
div.lastElementChild.scrollIntoView({ behavior: 'smooth' });

使用jQuery动画:

$('#DebugContainer').stop().animate({
  scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);

试试下面的代码:

const scrollToBottom = (id) => {
    const element = document.getElementById(id);
    element.scrollTop = element.scrollHeight;
}

你也可以使用Jquery使滚动平滑:

const scrollSmoothlyToBottom = (id) => {
    const element = $(`#${id}`);
    element.animate({
        scrollTop: element.prop("scrollHeight")
    }, 500);
}

下面是演示

下面是它的工作原理:

参考:scrollTop, scrollHeight, clientHeight

如果你使用jQuery scrollTop,这就简单多了:

$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);