自动滚动div

tar*_*rek 0 html css jquery

我有一个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>
Run Code Online (Sandbox Code Playgroud)

Roc*_*oC5 5

您可以通过设置scrollTop聊天窗口的属性来完成此操作div.要滚动到div的底部,请设置scrollTopscrollHeight:

var chatWindow = document.getElementById('chating');
chatWindow.scrollTop = chatWindow.scrollHeight;?
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Ln8Hd/

或者,使用jQuery:

var chatWindow = $("#chating");
chatWindow.scrollTop(chatWindow[0].scrollHeight);
Run Code Online (Sandbox Code Playgroud)

每次将聊天消息添加到div时,您都希望调用此方法.