使用 JavaScript 滚动溢出的 DIV
-
08-06-2019 - |
题
我有一个 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
内容的价值。
其他提示
这 滚动到视图 方法将元素滚动到视图中。
使用循环来迭代一个元素的 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);
我有一个 div 包裹了 3 个向左浮动的 div,并且其内容正在调整大小。当您尝试解决此问题时,为 div 包装器打开时髦颜色的边框/背景会有所帮助。问题是调整大小的 div 内容溢出到 div 包装器之外(并渗入包装器下方的内容区域下方)。
使用上面@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 包装器大小的 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') 生成包装器需要调整大小的高度。另外,我不知道有任何其他方法可以获取实际 jQuery 函数的滚动高度;$('#div-content').scrollTop() 和 $('#div-content').height 都不会产生真正的内容高度值。希望这对那里的人有帮助!