在聊天框中自动滚动javascript功能

时间:2017-12-09 22:50:46

标签: javascript jquery css chat autoscroll

如何在我的聊天框上实现向下滚动,因为我无法看到实时消息。我想让它在我的div id上被调用,我的风格溢出了

<script>
  //scroll to bottom
  window.onload=toBottom;
  function toBottom(){
    window.scrollTo(0, document.body.scrollHeight);
  }//end of scroll to bottom
</script>

查看部分

<div class="scrollMessage w3-padding div" onload="toBottom" id="scroll" style="overflow-y:scroll;height: 460px;">
      <?php include 'getMessage.php'; ?>        
</div>

首次加载时,它应该已经在最后一条消息上

在实际的聊天对话中,它也将显示在最后一条消息

1 个答案:

答案 0 :(得分:1)

这就是你要找的东西。希望,它有所帮助。

var objDiv = document.getElementById("scroll2"); //Obtain the ID of the chat div
window.onload = toBottom;
function toBottom() {
  objDiv.scrollTop = objDiv.scrollHeight; //Set the scroll offset position to the height of the chat div
}
<div id="scroll">
<div class="scrollMessage w3-padding div" onload="toBottom" id="scroll2" style="overflow-y:scroll;height: 200px;width:150px;">
  <!--<?php include 'getMessage.php'; ?>-->
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
  Random messages <br>
</div>
</div>