检查div是否滚动到底部,否则不做处理 [英] Check if div is scrolled to bottom, leave alone if not
问题描述
我最近开发了一个在线实时聊天室.我一切正常且安全,但是我希望将存储消息的div自动滚动到底部.我设法使用以下Javascript做到了这一点:
I recently developed a live online chat room. I have everything working and secure but I want the div that the messages are stored in to autoscroll to the bottom. I managed to do that with this Javascript:
window.setInterval(function() {
var elem = document.getElementById('messages');
elem.scrollTop = elem.scrollHeight;
}, 100);
但是,用户根本无法向上滚动,它总是将它们向下推回到div的底部.我想发生的是,如果用户已经在div的底部,那么当出现新消息时,它将用户滚动到div的底部.但是,如果用户不在div的底部,则不要理会它们,直到他们滚动到底部.
But with this, the user can't scroll upwards at all, it is always pushing them back down to the bottom of the div. What I want to happen is if the user is already at the bottom of the div, then when a new message appears it scrolls them to the bottom of the div. BUT if the user is NOT at the bottom of the div then leave them alone until they scroll to the bottom.
这是更新div的jQuery:
Here's the jQuery that updates the div:
window.onload = function(){
setInterval(function(){
$.ajax({
url: "get.php",
type: "GET",
success: function(output){
$("div#messages").html("<p>" + output + "</p>");
}
});
}, 500);
}
然后div本身从一开始就是空的:<div id="messages"></div>
Then the div itself is just empty from the start: <div id="messages"></div>
如果需要的话,这里是CSS:
Here's the CSS if you need it:
#messages {
width: 700px;
height: 250px;
border: 2px solid black;
overflow: auto;
-moz-border-radius: 15px;
border-radius: 15px;
}
jQuery和Javascript均可使用,我不限于使用其中一种.
Both jQuery and Javascript will work for this, I'm not restricted to using one or the other.
推荐答案
scrollTop
,在最大滚动时等于元素的scrollHeight
减去offsetHeight
.这是因为offsetHeight
包含在scrollHeight
中.
scrollTop
, at maximum scroll, will be equal to the scrollHeight
minus offsetHeight
of the element. This is because the offsetHeight
is included in the scrollHeight
.
将scrollTop
设置为scrollHeight
的原因在于浏览器会自动将变量调整为允许的最大滚动范围(scrollHeight - offsetHeight
).
Setting scrollTop
to scrollHeight
works because the browser automatically adjusts the variable to the maximum scroll allowed (scrollHeight - offsetHeight
).
这是您应该使用的逻辑:
Here's the logic you should use:
if (elem.scrollTop >= (elem.scrollHeight - elem.offsetHeight)) {
elem.scrollTop = elem.scrollHeight;
}
只需将if语句放在将elem.scrollTop
分配给elem.scrollHeight
Just slap the if statement around where you're assigning elem.scrollTop
to elem.scrollHeight
这篇关于检查div是否滚动到底部,否则不做处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!