我有一个div使用overflow:auto来保存div中的内容,因为它被调整大小并在页面上拖动。我正在使用一些ajax从服务器检索文本行,然后将它们附加到div的末尾,因此内容正在向下增长。每次发生这种情况时,我都希望使用JS将div滚动到底部,以便最近添加的内容可见,类似于聊天室或命令行控制台的工作方式。
到目前为止,我一直在使用这个代码片段(我也使用jQuery,因此使用$()函数):
$("#thediv").scrollTop = $("#thediv").scrollHeight;
然而,它给了我不一致的结果。有时它可以工作,有时不工作,如果用户调整div或手动移动滚动条,它就会完全停止工作。
目标浏览器是Firefox 3,它正在受控环境中部署,因此根本不需要在IE中工作。
任何想法的家伙?这个让我难过。谢谢!
答案 0 :(得分: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
个内容。
答案 1 :(得分:30)
scrollIntoView 方法将元素滚动到视图中。
答案 2 :(得分: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;
答案 3 :(得分:4)
$("#thediv").scrollTop($("#thediv")[0].scrollHeight);
答案 4 :(得分:0)
可以在普通JS中完成。技巧是将scrollTop设置为等于或大于元素的总高度(scrollHeight
)的值:
const theDiv = document.querySelector('#thediv');
theDiv.scrollTop = Math.pow(10, 10);
来自MDN:
如果设置的值大于该元素可用的最大值, scrollTop会将自身设置为最大值。
虽然Math.pow(10, 10)
的值使用Infintiy
或Number.MAX_VALUE
之类的太高的值来完成技巧,但会将scrollTop重置为0
(Firefox 66)。
答案 5 :(得分:-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都不会产生实际的内容高度值。希望这有助于那里的人!