我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
当前回答
如果这样做是为了滚动到聊天窗口的底部,请执行以下操作
在聊天中滚动到特定div的想法如下
1)每个聊天div由Person, time和message组成,在一个带有类chatContentbox的for循环中运行
2) querySelectorAll查找所有这样的数组。可以是400个节点(400个聊天)
3)最后一个
4) scrollIntoView ()
let lastChatBox = document.querySelectorAll('.chatContentBox');
lastChatBox = lastChatBox[lastChatBox.length-1];
lastChatBox.scrollIntoView();
其他回答
小附录:仅限滚动,如果最后一行已经可见。如果滚动一点点,将内容留在原地(注意:没有测试过不同的字体大小。这可能需要在">= 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;
如果您的项目针对现代浏览器,您现在可以使用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>
使用jQuery动画:
$('#DebugContainer').stop().animate({
scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);
你可以像这样使用HTML DOM scrollIntoView方法:
var element = document.getElementById("scroll");
element.scrollIntoView();
如果这样做是为了滚动到聊天窗口的底部,请执行以下操作
在聊天中滚动到特定div的想法如下
1)每个聊天div由Person, time和message组成,在一个带有类chatContentbox的for循环中运行
2) querySelectorAll查找所有这样的数组。可以是400个节点(400个聊天)
3)最后一个
4) scrollIntoView ()
let lastChatBox = document.querySelectorAll('.chatContentBox');
lastChatBox = lastChatBox[lastChatBox.length-1];
lastChatBox.scrollIntoView();