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

问题描述 投票:0回答:2

我有一个滚动视图,其中的内容正在通过 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 像素!

我该如何解决这个问题?

javascript html scroll scrollbar
2个回答
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>


0
投票

您面临的 900 的差异是因为视口/客户端高度。如果您将其添加到计算中,您会发现找到了

scrollHeight == scrollTop + clientHeight
。您可以在 Mozilla 基金会的 scrollHeight 文档中查看此内容。

© www.soinside.com 2019 - 2024. All rights reserved.