我有一个使用 Ajax 和 HTML 的简单聊天应用程序。 每当我加载新消息时,我想滚动 div 以显示最新的消息,因此我正在执行以下操作:
jQuery:
function SendMessage()
{
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '')
{
$.ajax(
{
type: 'POST',
url: url,
data:
{
email: email,
message: clientmsg
},
success: function (data)
{
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
$("#conversation").scrollTop($("#conversation").outerHeight() * 1000);
}
});
}
}
我使用这一行将 div 向下滚动到最大值:
$("#conversation").scrollTop($("#conversation").outerHeight()*1000);
我的问题是,它向下滚动到最大值WITHOUT showing the new messages。它向下滚动到新消息之前的最后一条消息。这很奇怪,因为我在更新聊天后调用它。这是更新聊天的函数:
function UpdateChat(){
$.ajax({
// URL that gives a JSON of all new messages:
url: "url",
success: function(result)
{
var objects = JSON.parse(result);
$("#conversation").html("");
objects.forEach(function(key, index){
//append the messages to the div
$("#conversation").append("html here");
});
}
});
};
最佳答案
如评论中所述,您可以使用 setTimeout()
让 dom 更新添加在滚动之前给一些时间。见下面的代码:
function SendMessage()
{
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '')
{
$.ajax(
{
type: 'POST',
url: url,
data:
{
email: email,
message: clientmsg
},
success: function (data)
{
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
setTimeout(function() {
$("#conversation").scrollTop($("#conversation").outerHeight() * 1000);
}, 500);
}
});
}
}
关于javascript - 在特定事件上向下滚动 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53006761/