2017-07-31 80 views
2

我有一个固定的高度div与动态内容。当某些内容添加到div时,我希望自动滚动到底部。我发现scrollTop = scrollHeight解决方案,但它不符合我的条件。滚动到具有动态内容的div的底部

$(document).ready(function(){ 
 
    var text = '<p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p>' 
 
    
 
    $("#content").html(text); 
 
    $("#content").scrollTop($('#content').scrollHeight) 
 
})
#content{ 
 
    max-height:250px; 
 
    overflow-y:auto; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="content"></div>

回答

0

变化

$("#content").scrollTop($('#content').scrollHeight) 

$("#content").scrollTop($('#content')[0].scrollHeight) 
+0

'.height()'会输出容器的高度(在本例中为250px,因为'max-height:250px'。这无助于获得“可滚动高度” –

+0

@MichaelWalter感谢指出出问题 – Ashish451

0

你可以试试这个代码:

这里是演示:https://output.jsbin.com/vobomafehi

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width"> 
    <title>JS Bin</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
    <script> 
    $(document).ready(function(){ 
     var text = '<p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p><p>some text</p>' 
     $("#content").html(text); 
     $("#content").scrollTop($('#content')[0].scrollHeight); 
    }); 
    </script> 
    <style> 
    #content{ 
     max-height:250px; 
     overflow-y:auto; 
    } 
    </style> 
</head> 
<body> 
<div id="content"></div> 
</body> 
</html> 
+0

你应该给你的答案提供一些解释 –

0

问题是$('#content').scrollHeight未定义。你要访问它是这样的: $('#content')[0].scrollHeight

小提琴:https://jsfiddle.net/sr8fnv4k/

为什么? 因为有些属性没有传递给jQuery。在这种情况下,您需要访问原始的HTML-Tag属性。