2017-07-31 83 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屬性。