使用JavaScript滚动溢出的DIV
时间:2020-03-05 18:40:06 来源:igfitidea点击:
我有一个使用overflow:auto的div,它在调整大小并在页面中拖动时将内容保留在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的内容。
回答
使用循环迭代一个元素的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;
回答
scrollIntoView
The scrollIntoView method scrolls the element into view.