2008-08-16 82 views
33

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

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

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

但是它已经给我不一致的结果。有时它有效,有时不起作用,如果用户调整了div的大小或手动移动滚动条,它就完全停止工作。

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

任何想法家伙?这个让我难住。谢谢!

回答

42

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价值的内容。

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; 
+2

不是那么低效,因为它只会迭代一次。然而,如果你打算在一秒钟内运行几次`each`,你肯定会注意到每次使用[0]时创建一个函数范围的开销;) – Kato 2011-11-29 00:01:04

26

scrollIntoView

scrollIntoView方法滚动元件到视图中。

+2

这在移动设备上不起作用,截至2015年9月。 – phreakhead 2015-09-11 07:17:30

3
$("#thediv").scrollTop($("#thediv")[0].scrollHeight); 
-1

我有一个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> 

这是我的jQuery来调整DIV-包装:

<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内容') .prop('scrollHeight')产生包装需要调整大小的高度。此外,我不知道任何其他方式来获得scrollHeight一个实际的jQuery函数; $('#div-content')。scrollTop()和$('#div-content')。height都不会产生真正的内容高度值。希望这可以帮助那里的人!