我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
当前回答
试试下面的代码:
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
其他回答
平滑滚动Javascript:
. getelementbyid(“信息”)。scrollIntoView({behavior: 'smooth', block: 'end'});
如果你使用jQuery scrollTop,这就简单多了:
$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
Css只有:
.scroll-container {
overflow-anchor: none;
}
使滚动条在添加子元素时不会停留在顶部。例如,当聊天底部添加新消息时,滚动聊天到新消息。
为什么不使用简单的CSS来做到这一点呢?
诀窍是使用display: flex;和弯曲方向:列反向;
Here is a working example. https://codepen.io/jimbol/pen/YVJzBg
我使用了第一个项目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>