我正在尝试进行实时聊天,并且正在使用此JS代码:
$(document).ready(function() {
// load messages every 1000 milliseconds from server.
load_data = {'fetch':1};
window.setInterval(function(){
$.post('shout.php', load_data, function(data) {
$('.message_box').html(data);
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
});
}, 1000);
//method to trigger when user hits enter key
$("#shout_message").keypress(function(evt) {
if(evt.which == 13) {
var iusername = $('#shout_username').val();
var imessage = $('#shout_message').val();
post_data = {'username':iusername, 'message':imessage};
//send data to "shout.php" using jQuery $.post()
$.post('shout.php', post_data, function(data) {
//append data into messagebox with jQuery fade effect!
$(data).hide().appendTo('.message_box').fadeIn();
//keep scrolled to bottom of chat!
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
//reset value of message box
$('#shout_message').val('');
}).fail(function(err) {
//alert HTTP server error
alert(err.statusText);
});
}
});
//toggle hide/show shout box
$(".close_btn").click(function (e) {
//get CSS display state of .toggle_chat element
var toggleState = $('.toggle_chat').css('display');
//toggle show/hide chat box
$('.toggle_chat').slideToggle();
//use toggleState var to change close/open icon image
if(toggleState == 'block')
{
$(".header div").attr('class', 'open_btn');
}else{
$(".header div").attr('class', 'close_btn');
}
});
});
资料来源:https://www.sanwebe.com/assets/chat-shout-box/
我的问题是,因为我正在使用
var scrolltoh = $('.message_box')[0].scrollHeight; $('.message_box').scrollTop(scrolltoh);
,每次重新加载页面时它始终滚动到底部。我正在尝试做的是,仅当某人发送新聊天时它才会滚动到底部。就像在Facebook上一样。
提前致谢。
最佳答案
请尝试这个:
// load messages every 1000 milliseconds from server.
load_data = {'fetch':1};
window.setInterval(function(){
$.post('shout.php', load_data, function(data) {
$('.message_box').html(data);
//var scrolltoh = $('.message_box')[0].scrollHeight; //try to replace this in other place just play with the code
//$('.message_box').scrollTop(scrolltoh);
});
}, 1000);
希望至少能有所帮助。
加上此代码:
function chatFunc(){
setTimeout(function() {
//your code to be executed after 1 second
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
}, 1000);
}
window.onload = chatFunc;