2012-12-11 138 views
0

我有一个div其中包含一个聊天框。每当有新消息到达时,它都会被附加到框中 - 我想自动将框移动到底部(以显示新消息)。我怎样才能做到这一点?自动滚动div

<div id="chatting" style="overflow: auto; background-color: #fff; border: solid 2px #dedede; width: 600px; height: 500px; padding: 10px;"> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
    hello<br/> 
</div> 
+0

[如何在添加数据时自动滚动到div末尾?](http://stackoverflow.com/questions/7303948/how-to-auto-scroll-to-end-of-div -when-data-is-added) –

+0

我不确定我是否理解这个问题。你想让页面在加载时滚动到底部吗? –

回答

5

您可以通过设置聊天窗口divscrollTop属性做到这一点。要滚动到div的底部,设置scrollTop等于scrollHeight

var chatWindow = document.getElementById('chating'); 
chatWindow.scrollTop = chatWindow.scrollHeight;​ 

http://jsfiddle.net/Ln8Hd/

或者,使用jQuery:

var chatWindow = $("#chating"); 
chatWindow.scrollTop(chatWindow[0].scrollHeight); 

你会想每次调用这个聊天消息已被添加到div。