我有一个 ScrollView ,其中的内容正在通过 ajax 查询刷新(增加其大小)。
我希望(就像所有IDE中常见的那样)当用户将滚动条放在底部时,即使添加更多文本,滚动条也必须保留在底部。
我尝试使用以下代码查找滚动条何时位于底部:
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
}
问题是,当用户在底部滚动时,scrollDiv[0].scrollTop 不等于scrollDiv[0].scrollHeight 我不明白为什么,但它少了大约 900 像素!
有没有人能解决这个问题?
最佳答案
您需要将高度
添加到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>
关于javascript - 仅当用户将其移动到底部时,如何在底部保持动态滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42208432/