简体   繁体   English

仅当用户将滚动条移动到底部时,才如何在底部保持动态滚动?

[英]How to maintain a dynamic scroll in bottom only if the user moves it to bottom?

I have a scrollview which has content that is being refreshed (increasing it's size) by a ajax query. 我有一个滚动视图,其中的内容正在被ajax查询刷新(增加其大小)。

I want that (like commonly in all the ides) when the user has the scroll on the bottom, the scroll must be mantained in the bottom even when adding more text. 当用户将滚动条放在底部时,我希望这样做(就像在所有ide中一样),即使添加更多文本,滚动条也必须放在底部。

I tryed to find when the scroll is in the bottom with this code: 我尝试使用以下代码查找滚动条何时位于底部:

var scrollDiv = $('#modalText');
var height = scrollDiv[0].scrollHeight;
if (scrollDiv[0].scrollTop==height){
 //scroll is in the bottom, must force the scroll to bottom
}else{
 //scroll is not in the bottom, must maintain the scroll point
}

The problem is that scrollDiv[0].scrollTop is not equal to scrollDiv[0].scrollHeight when the user has the scroll in the bottom I can't understand why, but it's about 900 pixels less! 问题是,当用户在底部滚动时,scrollDiv [0] .scrollTop不等于scrollDiv [0] .scrollHeight我不明白为什么,但是它少了900像素!

Does anyone has any solution for this? 有人对此有任何解决方案吗?

you need to add the height to scrollTop to get scrollBottom 您需要将height添加到scrollTop以获得scrollBottom

 var scrollDiv = $('#modalText'); function add() { var height = scrollDiv[0].scrollHeight; var scroll = scrollDiv[0].scrollTop + scrollDiv[0].offsetHeight; scrollDiv.append('<p>' + Number(new Date()) + '</p>'); if (scroll == height) { //scroll is in the bottom, must force the scroll to bottom scrollDiv.scrollTop(height); } else { //scroll is not in the bottom, must maintain the scroll point } }; 
 #modalText { max-height: 180px; overflow: auto; width: 200px; background-color: #f5f5f5; padding: 10px; box-sizing: border-box; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button onclick="add()">Add</button> <div id="modalText"></div> 

The difference of 900 you are facing is because because of the viewport/client height. 您面临的900的差异是因为视口/客户端的高度。 If you add that to the calculations you'll see that find that scrollHeight == scrollTop + clientHeight . 如果将其添加到计算中,您会发现找到scrollHeight == scrollTop + clientHeight You may review this at Mozilla Foundation's documentation of scrollHeight . 您可以在Mozilla Foundation的scrollHeight文档中进行查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM