简体   繁体   English

聊天框滚动到底部

[英]Chat box scroll to bottom

I have found a solution here on Stackoverflow but I can't get it working 我在这里找到了关于Stackoverflow的解决方案,但是我无法正常工作

...
<div class="panel-body">
    <ul id="mtchat" class="chat">

    </ul>
</div>
...

And here the js it adds the new <li> but scrolling doesn't work 在这里,js添加了新的<li>但是滚动不起作用

worker();

function worker() {

  // ajax request deleted

  updateChat();
  setTimeout(worker, 1000);

};

function updateChat() {

  $('#mtchat').append('<li class="right clearfix">Hallo</li>');

  var height = $('#mtchat')[0].scrollHeight;
  var dheight = $('#mtchat').height();
  var scrolling = height - dheight;
  $('#mtchat').scrollTop(scrolling);
  console.log('height:'+height);
  console.log('dheight:'+dheight);

}

In the console, I can see scrollHeight and Height is always the same even if the overflow starts. 在控制台中,即使溢出开始,我也可以看到scrollHeightHeight始终相同。

I have made a JsBin 我做了一个JsBin

Check this jsfiddle 检查这个jsfiddle

In here, worker() method is only been called once and this in return just sets up the stuff for us: 在这里, worker()方法仅被调用一次,而这只是为我们设置了东西:

  • Adding one "Hallo" as welcome message, only once 仅添加一次“ Hallo”作为欢迎消息
  • Assigning the handler for button click button单击分配处理程序
  • Timer for updating the chat box 计时器更新聊天框

Code : 代码:

function worker() {

  $('#mtchat').append('<li class="right clearfix">Hallo</li>');
  // ajax request deleted
  setTimeout(updateChat(), 1000);
  $("#btn-chat").on("click", function(){
    var text = $('#btn-input');
    $('#mtchat').append('<li class="right clearfix">'+ text.val() +'</li>');
    text.val('');
  });
};

function updateChat() {
  var height = document.getElementById('mtchat').scrollHeight; - $('#mtchat').height(); 
  $('#mtchat').scrollTop(height);
}

Your JS Bin does not include the jquery library in the head. 您的JS Bin头部不包含jquery库。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>

Include the above within the head tag 将以上内容包含在head标签中

Also the following line should be fixed as below: 另外,以下行应固定为:

var height = document.getElementById('mtchat').scrollHeight; - $('#mtchat').height();

to

var height = $('#mtchat')[0].scrollHeight - $('#mtchat').height();

$('#mtchat')[0].scrollHeight is jquery way of writing document.getElementById('mtchat').scrollHeight $('#mtchat')[0].scrollHeight是编写document.getElementById('mtchat').scrollHeight jquery方法

Since you are using jquery everywhere else. 由于您在其他任何地方都使用jquery。

I've figured out now. 我现在想通了。 .panel-body was intended to overflow but I checked the scrollHeight of the <ul> in the div.panel-body . .panel-body旨在overflow ,但我检查了scrollHeight<ul>div.panel-body

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM