我有一个div使用overflow:auto来保持div内的内容,因为它被调整大小并在页面上拖动。我正在使用一些ajax从服务器检索文本行,然后将它们附加到div的末尾,因此内容正在向下增长。每次发生这种情况时,我都希望使用JS将div滚动到底部,以便最近添加的内容可见,类似于聊天室或命令行控制台的工作方式。
到目前为止,我一直在使用这个代码片段(我也使用jQuery,因此$()函数):
$("#thediv").scrollTop = $("#thediv").scrollHeight;
然而,它给了我不一致的结果。有时它可以工作,有时不工作,如果用户调整div或手动移动滚动条,它就会完全停止工作。
目标浏览器是Firefox 3,它被部署在受控环境中,因此根本不需要在IE中工作。
有什么想法吗?这个让我难过。谢谢!
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
值的内容。
scrollIntoView方法将元素滚动到视图中。
使用循环迭代一个元素的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;
$("#thediv").scrollTop($("#thediv")[0].scrollHeight);
我有一个包含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都不会产生实际的内容高度值。希望这有助于那里的人!