Javascript 附加后使用jQuery自动滚动div到底部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11153707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Autoscroll div with jQuery to the bottom after appending
提问by f1nn
I have a div class='messages'. I add date to this div via jQuery.append() Here are the styles:
我有一个 div class='messages'。我通过 jQuery.append() 向这个 div 添加日期这里是样式:
.messages {
border: 1px solid #dddddd;
padding:10px;
height: 400px;
overflow-x:visible;
overflow-y: scroll;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
margin-bottom:10px;
font-size:14px;
}
For autoscroll I use such function:
对于自动滚动,我使用这样的功能:
receiveMessage = function (name, message, type) {
//adding new message
$("#messages").append('<strong>' + name + ": " + '</strong>' + message + '<br>');
/autoscrolling to the bottom
$("#messages").animate({
scrollTop: $("#messages").height()
}, 300);
}
About ~20 messages are scrolling normally, but after it 'hangs', new messages are not scrolled. Chrome Version 19.0.1084.56 . What I'm doing wrong? Thanks!
大约 20 条消息正常滚动,但在“挂起”后,新消息不会滚动。Chrome 版本 19.0.1084.56。我做错了什么?谢谢!
采纳答案by Raab
Change
改变
scrollTop: $("#messages").height()
to
到
scrollTop: $("#messages").scrollHeight
回答by Jeffrey L. Roberts
This solution did not work for me, however, the following did...
这个解决方案对我不起作用,但是,以下确实......
$(document).ready(function(){
$('#chat-scroll').animate({
scrollTop: $('#chat-scroll').get(0).scrollHeight}, 2000);
});
回答by Chintan Patel
Please try:
请尝试:
$(document).ready(function(){
$('#chat-scroll').animate({scrollTop: $('#chat-scroll')[0].scrollHeight}, 2000);
});