我有一个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像素!
有没有人对此有任何解决方案?
答案 0 :(得分:1)
您需要将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>
答案 1 :(得分:0)
您面临的900差异是因为视口/客户端高度。如果将其添加到计算中,您会看到找到scrollHeight == scrollTop + clientHeight
。您可以在Mozilla Foundation的scrollHeight文档中查看此内容。