【发布时间】:2018-10-26 10:31:33
【问题描述】:
我有一个使用 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);
我的问题是,它向下滚动到最大值不显示新消息。它向下滚动直到新消息之前的最后一条消息。这很奇怪,因为我在更新聊天后调用它。这是更新聊天的功能:
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");
});
}
});
};
【问题讨论】:
-
您是否尝试过查看滚动命令是否在 ajax 调用的外部工作?基本上假设 ajax 调用是成功的。
-
@thisiskelvin ajax 成功,因为消息已保存到数据库中。在浏览器的控制台上测试时,滚动命令运行良好
-
可能在
ajax调用内,dom 已在 dom 中注册了更改(就容器新高度而言。解决方法可能是在setTimeout()内调用,给时间识别变化。 -
您希望我在答案中显示吗?
-
如果您在顶部添加新消息(即 - 将它们放在前面而不是附加它们),那么您将不必担心滚动,并且较新的消息只是位于列表顶部并且可以访问无需滚动。
标签: javascript jquery html ajax