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

标签 javascript html scroll scrollbar

我有一个 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/

相关文章:

javascript - 模拟固定的侧边栏模板问题

javascript - 为什么剪切、复制、粘贴在 Mozilla Firefox 和 Google Chrome 浏览器中不起作用?

html - 如何将 3 个 block (span、span、input)放置在垂直对齐的一行中?

ios - 无法在 UICollectionViewController 上平滑滚动以加载大量数据

javascript - 在 Codepen 元素中使用 fullpage.js 时遇到问题

javascript - 在 JavaScript 中显示数组 onclick 中的下一项

javascript - 如何获取html内容宽度而不是窗口宽度

python - 使用 smtplib.SMTP.sendmail 发送 HTML 消息时电子邮件被截断

javascript - 像 Facebook 一样禁用带有叠加层的滚动

javascript - 滚动触发后运行 .animate() 一次