Check if div is scrolled to bottom, leave alone if not

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

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); 

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.

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);          } 

Then the div itself is just empty from the start: <div id="messages"></div>

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; } 

Both jQuery and Javascript will work for this, I'm not restricted to using one or the other.

回答1:

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.

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; } 

Just slap the if statement around where you're assigning elem.scrollTop to elem.scrollHeight



回答2:

You can do this easily by altering your second code block to the following and removing the first code block.

window.onload = function(){     setInterval(function(){         $.ajax({           url: "get.php",           type: "GET",           success: function(output){                var elem = document.getElementById('messages');               var scrollToBottom = false;               if(elem.scrollTop == elem.scrollHeight){                    scrollToBottom = true;               }                $(elem).html("<p>" + output + "</p>");               if(scrollToBottom ){                    elem.scrollTop = elem.scrollHeight;               }         });     }, 500); } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!