gpt4 book ai didi

javascript - 在特定事件上向下滚动 div

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

我有一个使用 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/

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