在特定事件下向下滚动div

时间:2018-10-26 10:31:33

标签: 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);

我的问题是,它向下滚动到最大没有显示新消息。向下滚动直到新消息之前的最后一条消息。太奇怪了,因为我是在更新聊天内容后调用它的。这是更新聊天功能:

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");
              });
            }
      });
  };

3 个答案:

答案 0 :(得分:1)

如注释中所述,您可以使用SELECT CONCAT( LEFT(your_column, LENGTH(your_column) - LOCATE('.', REVERSE(your_column))+1), CAST(SUBSTRING_INDEX(your_column, '.', -1) AS UNSIGNED) +1 ) 让dom更新添加一些滚动时间。参见下面的代码:

SELECT CONCAT(
    LEFT("2.2.2", LENGTH("2.2.2") - LOCATE('.', REVERSE("2.2.2"))+1),  
        CAST(SUBSTRING_INDEX("2.2.2", '.', -1) AS UNSIGNED) +1
)

答案 1 :(得分:0)

请尝试将滚动行放在setTimeout()方法内,以允许约500ms的内容在向下滚动之前进行更新。

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();

                setTimeout(performScroll, 500);

              }
          });
    }
}

和滚动功能

function performScroll() {  
  $("#conversation").scrollTop($("#conversation").outerHeight()*1000);
}

答案 2 :(得分:0)

假设您在底部插入一个新元素,则可以使用scrollIntoView确保该新元素可见:

$.ajax({
    // ...
    success: function(data) {
        var lastElement = $('#conversation :last-child');
        lastElement[0].scrollIntoView();
    }
});