我正在创建一个chatbox。当用户键在msg中时,它应该立即出现在chatbox中。滚动条应该始终滚动到chatbox的底部。下面的代码确实有效,但是当我试图将条形图滚动到顶部以查看以前的msg时,它总是会被拖回底部。我不确定是因为setInterval。知道怎么解决这个问题吗?
$(function(){
$("#textmsg").keypress(function (e) {
if (((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) && !e.shiftKey){
$('.post').click();
return false;
} else {
return true;
}
});
$(document).on('submit','#discussionForm',function(){
var textmsg = $.trim($("#textmsg").val());
var name = $.trim($("#name").val());
if(textmsg != "" && name!=""){
$.post('inc/postMessages.php', $("#discussionForm").serialize(), function(data){
$(".discussionMessages").html(data);
});
$("#textmsg").val('');
}else{
alert("Please enter some text!");
}
});
setInterval(function(){
getMessages();
},800);
});
function getMessages(){
$.get('inc/getMessages.php', function(data){
var message = $(".discussionMessages");
message.html(data);
message.scrollTop(message[0].scrollHeight);
});
}我已经查看了这篇文章,AJAX Chat Box Scrolling Up Issue,但是我不太确定如何应用到我的代码中。
发布于 2015-05-23 20:52:54
每800毫秒加载一次整个会话是非常低效的--您应该确保每次加载时只获取新消息,或者更好地切换到websockets或类似的内容。但是,我不知道您的用例,我不会详细说明这一点,因为这不是您要问的问题。
因此,要回答你的问题:你需要做的只是在发布新内容时滚动,所以只需跟踪和比较之前的内容和新内容,只做一些事情--如果它们不相等,就包括滚动:
var old_content = '';
function getMessages(){
$.get('inc/getMessages.php', function(data){
if (data !== old_content) {
var message = $(".discussionMessages");
message.html(data);
message.scrollTop(message[0].scrollHeight);
old_content = data;
}
});
}如果您不希望它滚动,即使当用户从底部滚动出新消息时,您也可以添加一个检查:
var old_content = '';
function getMessages(){
$.get('inc/getMessages.php', function(data){
if (data !== old_content) {
var message = $(".discussionMessages");
/* scrollTop gives the position from the top, while
* scrollheight gives the entire content height - so
* we need to add the innerHeight (ie. height of the
* scrollable element) to get the bottom of the current
* view - you actually ought to subtract the innerHeight
* from the scroll function itself too, it just doesn't
* matter as long as the value you pass is larger than
* the scrollHeight it will hit the bottom...
*/
var do_scroll = (message.scrollTop() + message.innerHeight() >= message[0].scrollHeight);
message.html(data);
if (do_scroll) message.scrollTop(message[0].scrollHeight);
old_content = data;
}
});
}https://stackoverflow.com/questions/30415961
复制相似问题