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

标签 javascript jquery html ajax

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

相关文章:

javascript - jQuery:如何删除单击切换上的附加项目

html - 水平显示嵌套 UL 的垂直导航菜单

html - Angular2 从一个组件导航到同级组件而不拆除第一个组件

html - 两列并排

javascript - 警报,当在 mysql 数据库中找不到搜索词时

javascript - zend Framework 2 操作中带有 javascript 的警报框

javascript - 这个节点/快速路由如何完成更新?或者确实如此?

javascript - 来自 Postman 的 HTTP Post 可以工作,但不能通过浏览器

jquery - 如何删除按钮上的默认 Bootstrap 效果 appyid?

javascript - 如何阻止 JS 函数在移动设备上运行?