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

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

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

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

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


当前回答

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

//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' });

其他回答

如果你不想依赖scrollHeight,下面的代码可以帮助你:

$('#scroll').scrollTop(1000000);

我使用了第一个项目div的Y坐标和所选项目div的Y坐标之间的差异。下面是JavaScript/JQuery代码和html:

function scrollTo(event){ // In my proof of concept, I had a few <button>s with value // attributes containing strings with id selector expressions // like "#item1". let selectItem = $($(event.target).attr('value')); let selectedDivTop = selectItem.offset().top; let scrollingDiv = selectItem.parent(); let firstItem = scrollingDiv.children('div').first(); let firstItemTop = firstItem.offset().top; let newScrollValue = selectedDivTop - firstItemTop; scrollingDiv.scrollTop(newScrollValue); } <div id="scrolling" style="height: 2rem; overflow-y: scroll"> <div id="item1">One</div> <div id="item2">Two</div> <div id="item3">Three</div> <div id="item4">Four</div> <div id="item5">Five</div> </div>

小附录:仅限滚动,如果最后一行已经可见。如果滚动一点点,将内容留在原地(注意:没有测试过不同的字体大小。这可能需要在">= compare "中进行一些调整):

var objDiv = document.getElementById(id);
var doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight);                   

// add new content to div
$('#' + id ).append("new line at end<br>"); // this is jquery!

// doScroll is true, if we the bottom line is already visible
if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;

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

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

我知道这是一个老问题,但这些解决方案对我都不起作用。我最终使用offset()。顶部得到想要的结果。以下是我在聊天应用程序中轻轻向下滚动屏幕到最后一条消息的方法:

$("#html, body").stop().animate({
     scrollTop: $("#last-message").offset().top
}, 2000);

我希望这能帮助到其他人。