Javascript 聊天框滚动至底部
我在Stackoverflow上找到了一个解决方案,但我无法让它工作Javascript 聊天框滚动至底部,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我在Stackoverflow上找到了一个解决方案,但我无法让它工作 ... <div class="panel-body"> <ul id="mtchat" class="chat"> </ul> </div> ... 。。。 ... 在这里,jsit添加了新的,但是滚动不起作用 worker(); function worker() { // ajax request deleted updateChat
...
<div class="panel-body">
<ul id="mtchat" class="chat">
</ul>
</div>
...
。。。
...
在这里,jsit添加了新的
,但是滚动不起作用
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);
}
worker();
功能工人(){
//已删除ajax请求
updateChat();
setTimeout(工人,1000);
};
函数updateChat(){
$(“#mtchat”).append(“Hallo ”);
var height=$('#mtchat')[0];
var dheight=$('#mtchat').height();
var滚动=高度-dheight;
$('#mtchat')。滚动顶端(滚动);
console.log('高度:'+高度);
log('dheight:'+dheight);
}
在控制台中,我可以看到scrollHeight
和Height
始终相同,即使溢出开始
我做了一个检查
在这里,worker()
方法只被调用一次,作为回报,它只为我们设置了内容:
- 添加一个“哈罗”作为欢迎信息,仅一次
- 为
单击按钮指定处理程序
- 更新聊天室的计时器
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);
}
functionworker(){
$(“#mtchat”).append(“Hallo ”);
//已删除ajax请求
setTimeout(updateChat(),1000);
$(“#btn聊天”)。在(“单击”,函数()上{
变量文本=$(“#btn输入”);
$(“#mtchat”).append(“”+text.val()+” ”);
text.val(“”);
});
};
函数updateChat(){
var height=document.getElementById('mtchat').scrollHeight;-$('mtchat').height();
$('#mtchat')。滚动顶部(高度);
}
您的JS Bin在头部不包含jquery库
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
到
$('#mtchat')[0]。scrollHeight
是jquery编写文档的方式。getElementById('mtchat')。scrollHeight
因为您在其他地方都在使用jquery。我现在明白了。
.panel-body
本打算溢出
,但我在div.panel-body
中检查了
的滚动高度
是否添加了jquery?我在你的jsbin中看不到它…这将大大阻碍这段代码的工作,因为它需要jquery。谢谢你,我现在修复了jsbin。不,这不是我想要的。而且你也不会自动滚动(工作人员只是定期通过ajax阅读聊天伙伴的新更新。我删除了ajax请求,因为不需要演示。我的问题只是自动滚动。谢谢,我现在修复了jsbin,但自动滚动不起作用(即使使用您建议的jquery版本)
var height = document.getElementById('mtchat').scrollHeight; - $('#mtchat').height();
var height = $('#mtchat')[0].scrollHeight - $('#mtchat').height();