【问题标题】:Automatically scrolling a div自动滚动 div
【发布时间】:2012-11-29 07:19:36
【问题描述】:

我有一个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>

【问题讨论】:

标签: jquery html css


【解决方案1】:

您可以通过设置聊天窗口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 添加聊天消息时调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 2016-12-27
    • 1970-01-01
    相关资源
    最近更新 更多