使用JavaScript滚动溢出的DIV

问题描述 投票:37回答:6

我有一个div使用overflow:auto来保持div内的内容,因为它被调整大小并在页面上拖动。我正在使用一些ajax从服务器检索文本行,然后将它们附加到div的末尾,因此内容正在向下增长。每次发生这种情况时,我都希望使用JS将div滚动到底部,以便最近添加的内容可见,类似于聊天室或命令行控制台的工作方式。

到目前为止,我一直在使用这个代码片段(我也使用jQuery,因此$()函数):

$("#thediv").scrollTop = $("#thediv").scrollHeight;

然而,它给了我不一致的结果。有时它可以工作,有时不工作,如果用户调整div或手动移动滚动条,它就会完全停止工作。

目标浏览器是Firefox 3,它被部署在受控环境中,因此根本不需要在IE中工作。

有什么想法吗?这个让我难过。谢谢!

javascript jquery ajax html scroll
6个回答
43
投票

scrollHeight应该是内容的总高度。 scrollTop指定要在元素客户区顶部显示的内容的像素偏移量。

所以你真的想要(仍然使用jQuery):

$("#thediv").each( function() 
{
   // certain browsers have a bug such that scrollHeight is too small
   // when content does not fill the client area of the element
   var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);
   this.scrollTop = scrollHeight - this.clientHeight;
});

...将滚动偏移设置为最后一个clientHeight值的内容。


30
投票

scrollIntoView

scrollIntoView方法将元素滚动到视图中。


6
投票

使用循环迭代一个元素的jQuery是非常低效的。选择ID时,您可以使用get()或[]表示法检索jQuery的第一个和唯一元素。

var div = $("#thediv")[0];

// certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(div.scrollHeight, div.clientHeight);
div.scrollTop = scrollHeight - div.clientHeight;

4
投票
$("#thediv").scrollTop($("#thediv")[0].scrollHeight);

0
投票

它可以在普通的JS中完成。诀窍是将scrollTop设置为等于或大于元素总高度的值(scrollHeight):

const theDiv = document.querySelector('#thediv');
theDiv.scrollTop = Math.pow(10, 10);

来自MDN

如果设置为大于元素可用的最大值,则scrollTop将自身设置为最大值。

虽然Math.pow(10, 10)的价值使用像InfintiyNumber.MAX_VALUE这样过高的值,但会将scrollTop重置为0(Firefox 66)。


-1
投票

我有一个包含3个div的div,它们左侧浮动,其内容正在调整大小。当您尝试解决此问题时,它有助于为div-wrapper打开时髦的边框/背景。问题是调整大小的div-content在div-wrapper之外溢出(并且流到包装器下面的内容区域下面)。

通过使用@ Shog9的上述答案解决。适用于我的情况,这是HTML布局:

<div id="div-wrapper">
  <div class="left-div"></div>
  <div id="div-content" class="middle-div">
  Some short/sweet content that will be elongated by Jquery.
  </div>
  <div class="right-div"></div>
</div>

这是我调整div-wrapper大小的jQuery:

<script>
$("#div-content").text("a very long string of text that will overflow beyond the width/height of the div-content");
//now I need to resize the div...
var contentHeight = $('#div-content').prop('scrollHeight')
$("#div-wrapper").height(contentHeight);
</script>

要注意,$('#div-content')。prop('scrollHeight')生成包装器需要调整大小的高度。另外我不知道有任何其他方法来获取scrollHeight一个实际的jQuery函数; $('#div-content')。scrollTop()和$('#div-content')。height都不会产生实际的内容高度值。希望这有助于那里的人!

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