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

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

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

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

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


当前回答

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

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

其他回答

只是作为一个额外的片段。我正在使用angular,并试图在用户选择与用户的不同对话时将消息线程滚动到底部。为了确保在使用ng-repeat for消息将新数据加载到div之后滚动仍然有效,只需在超时时间内包装滚动片段。

$timeout(function(){
    var messageThread = document.getElementById('message-thread-div-id');
    messageThread.scrollTop = messageThread.scrollHeight;
},0)

这将确保在数据插入DOM之后触发滚动事件。

我使用了第一个项目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>

如果您的项目针对现代浏览器,您现在可以使用CSS Scroll Snap来控制滚动行为,例如将任何动态生成的元素保持在底部。

.wrapper > div { background-color: white; border-radius: 5px; padding: 5px 10px; text-align: center; font-family: system-ui, sans-serif; } .wrapper { display: flex; padding: 5px; background-color: #ccc; border-radius: 5px; flex-direction: column; gap: 5px; margin: 10px; max-height: 150px; /* Control snap from here */ overflow-y: auto; overscroll-behavior-y: contain; scroll-snap-type: y mandatory; } .wrapper > div:last-child { scroll-snap-align: start; } <div class="wrapper"> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> <div>07</div> <div>08</div> <div>09</div> <div>10</div> </div>

var mydiv = $("#scroll");
mydiv.scrollTop(mydiv.prop("scrollHeight"));

来自jQuery 1.6的工作

https://api.jquery.com/scrollTop/

http://api.jquery.com/prop/

一个非常简单的方法是将滚动设置为div的高度。

var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);