[英]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. 在控制台中,即使溢出开始,我也可以看到scrollHeight
和Height
始终相同。
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()
方法仅被调用一次,而这只是为我们设置了东西:
button
click 为button
单击分配处理程序 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.