我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
当前回答
我发现这真的很有用,谢谢。
对于Angular 1。在座的X位朋友:
angular.module('myApp').controller('myController', ['$scope', '$document',
function($scope, $document) {
var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');
overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;
}
]);
只是因为在jQuery元素和HTML DOM元素中包装有点让人困惑。
同样对于聊天应用程序,我发现在你的聊天加载后进行分配是有用的,你也可能需要在短的超时。
其他回答
使用jQuery, scrollTop用于为任何给定元素设置scollbar的垂直位置。还有一个漂亮的jquery scrollTo插件,用于滚动动画和不同的选项(演示)
var myDiv = $("#div_id").get(0);
myDiv.scrollTop = myDiv.scrollHeight;
如果你想使用jQuery的animate方法在向下滚动时添加动画,请检查下面的代码片段:
var myDiv = $("#div_id").get(0);
myDiv.animate({
scrollTop: myDiv.scrollHeight
}, 500);
将到可滚动元素顶部的距离设置为元素的总高度。
const element = this.shadowRoot.getElementById('my-scrollable-div')
element.scrollTop = element.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>
如果你不想依赖scrollHeight,下面的代码可以帮助你:
$('#scroll').scrollTop(1000000);
可选择的解决方案
function scrollToBottom(element) {
element.scroll({ top: element.scrollHeight, behavior: 'smooth' });
}