gpt4 book ai didi

javascript - 如何防止在 php JS 中重新加载 div 中的 scrollHeight?

转载 作者:行者123 更新时间:2023-11-30 20:37:38 26 4
gpt4 key购买 nike

我正在尝试进行实时聊天并且正在使用此 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;

关于javascript - 如何防止在 php JS 中重新加载 div 中的 scrollHeight?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com