我有一个聊天应用程序,当收到新消息时,它会自动滚动到 div 底部。除非您向上滚动以阅读日志,否则这种方法效果很好,因为当收到新消息时,它会跳回底部。仅当滚动位置已位于底部且不知道如何操作时,我才需要它滚动。
var scroll = $("div#log").prop("scrollHeight") - $('div#log').height()
$("div#log").scrollTop(scroll)
任何帮助/建议将受到欢迎和赞赏:)
您可以使用 $(document).scrollTop() 和 window.innerHeight 来实现。
function appendMessage(message) {
if($(document).scrollTop() + window.innerHeight == $('body').height())
/* append message and scroll */
else
/* append message without scroll */
});
看我的小提琴:http://jsfiddle.net/sxR9j/
您必须在滚动事件上有一个处理程序来检查您是否位于滚动的底部。
$("#mydiv").on('scroll', function() {
...
}
您可以通过从scrollHeight属性中减去scrollTop和clientHeight属性来检查是否位于滚动底部,请参阅我的小提琴:http://jsfiddle.net/XS3kf/1/
一种方法是从容器的
height
(内容的完整高度)中减去容器的 scrollHeight
(可见部分),这样您就可以得到相对于容器底部的视图偏移量。
如果该数量大于或等于
scrollTop
(用户当前滚动到的视图顶部),则启用自动滚动。
否则,用户的
scrollTop
太靠上;不要自动滚动。
最重要的是,我喜欢添加一点缓冲区量,例如 50 像素,这样即使用户滚动得足够靠近容器底部,自动滚动也会启动。
const list = document.querySelector("ul");
setInterval(() => {
const item = document.createElement("li");
item.textContent = new Date().toISOString();
list.append(item);
const { height } = list.getBoundingClientRect();
if (list.scrollTop >= list.scrollHeight - height - 50) {
list.scrollTop = list.scrollHeight;
}
}, 500);
ul {
overflow-y: scroll;
height: 200px;
border: 1px solid black;
}
<ul></ul>
和 jQuery:
const list = $("ul");
setInterval(() => {
const item = $("<li></li>").text(new Date().toISOString());
list.append(item);
const { height } = list[0].getBoundingClientRect();
if (list.scrollTop() >= list[0].scrollHeight - height - 50) {
list.scrollTop(list[0].scrollHeight);
}
}, 500);
ul {
overflow-y: scroll;
height: 200px;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<ul></ul>