我从多个教程中找到了这个 AJAX 代码,但问题是,当调用 ajax 时,div 总是滚动到底部。但我希望它只有在 div 中有新消息时 div 才会滚动。
$.ajax({
url: "msg-handle/get-messages.php",
cache: false,
data: { room: $("#room").val() },
success: function(data) { $('#chat').html(data)
$("#chat").scrollTop($("#chat")[0].scrollHeight);
},
});
}, 500);
有没有办法在不对我的代码产生任何重大影响的情况下实现这一点?
最佳答案
我没有尝试过,但我认为它必须是这样的......(在其他解决方案中)
var oldscrollHeight = $("#chat")[0].scrollHeight;
//Takes the height BEFORE reload the div
$.ajax({
url: "msg-handle/get-messages.php",
cache: false,
data: { room: $("#room").val() },
success: function(data) { $('#chat').html(data)
var newscrollHeight = $("#chat")[0].scrollHeight;
//Takes the height AFTER reload the div
if(newscrollHeight > oldscrollHeight){ //COMPARES
$("#chat").scrollTop($("#chat")[0].scrollHeight); //Scrolls
}
},
});
我认为你必须在第一次加载聊天后放置一个 $("#chat").scrollTop($("#chat")[0].scrollHeight);
..只是一个建议。
关于javascript - JQuery 聊天应用程序仅在收到新消息时滚动到 div 的底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9153975/