我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
当前回答
Javascript或jquery:
var scroll = document.getElementById('messages');
scroll.scrollTop = scroll.scrollHeight;
scroll.animate({scrollTop: scroll.scrollHeight});
Css:
.messages
{
height: 100%;
overflow: auto;
}
其他回答
我知道这是一个老问题,但这些解决方案对我都不起作用。我最终使用offset()。顶部得到想要的结果。以下是我在聊天应用程序中轻轻向下滚动屏幕到最后一条消息的方法:
$("#html, body").stop().animate({
scrollTop: $("#last-message").offset().top
}, 2000);
我希望这能帮助到其他人。
我使用了第一个项目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>
使用jQuery动画:
$('#DebugContainer').stop().animate({
scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);
如果你使用jQuery scrollTop,这就简单多了:
$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
你可以像这样使用HTML DOM scrollIntoView方法:
var element = document.getElementById("scroll");
element.scrollIntoView();