我正在开发一个聊天系统。我需要滚动条保持在底部,除非用户向上滚动,如果用户向上滚动它们应该保持原样,除非它们向下滚动并锁定回滚动。我相信这叫做“粘性卷轴”。
我写的Javascript并没有保存旧的高度。控制台显示,var oldHeight = (out.scrollHeight - out.clientHeight);
作为问题应该正常工作。
我想知道是否有人知道更好的方法来做这个或如果有人知道为什么var不起作用。谢谢!
function my_function() {
var out = document.getElementById("Mess2");
var oldHeight = (out.scrollHeight - out.clientHeight);
$('#Mess2').load("#Mess2" + ' #message_area');
var isScrolledToBottom = (out.scrollHeight - out.clientHeight >= oldHeight) && (oldHeight <= out.scrollTop);
console.log(oldHeight, out.scrollHeight - out.clientHeight, out.scrollTop);
if (isScrolledToBottom)
out.scrollTop = out.scrollHeight - out.clientHeight;
}
setInterval("my_function();", 1000);
如评论中所述,使用$("#chat").scrollTop($('#chat')[0].scrollHeight);
滚动,滚动的触发应由用户是否向上滚动确定,如果它们滚动回到底部,则再次启用滚动。
例:
$(function() {
var chatElm = $("#chat");
// turn on/off scrolling
var autoScroll = true;
chatElm.scroll(function() {
autoScroll = false;
// if height == scroll pos enable scrolling (ie, at bottom)
if (chatElm.scrollTop() + chatElm.height() === chatElm[0].scrollHeight) {
autoScroll = true;
}
});
// scroll to bottom of div
function scrollToBottom() {
chatElm.scrollTop(chatElm[0].scrollHeight);
}
var i = 0;
setInterval(function() {
i++;
chatElm.append(i + '<br>');
// to scroll or not to scroll
!autoScroll || scrollToBottom();
}, 300);
})
#chat {
height: 100px;
background: #ccc;
overflow-y: auto
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat"></div>