简体   繁体   English

JQuery聊天应用程序只在新消息上滚动到div的底部?

[英]JQuery chat application scroll to bottom of div ONLY on new message?

I have picked up this AJAX code from multiple tutorials, but the problem is, when the ajax is called, the div ALWAYS scrolls to the bottom. 我从多个教程中选择了这个AJAX代码,但问题是,当调用ajax时,div总是滚动到底部。 But I want it so that the div ONLY scrolls if there are new messages in the div. 但是我想要它,以便div只有在div中有新消息时滚动。

$.ajax({
  url: "msg-handle/get-messages.php",
  cache: false,
  data: { room: $("#room").val() },
  success: function(data) { $('#chat').html(data)

$("#chat").scrollTop($("#chat")[0].scrollHeight);

  },
});

}, 500);

Is there a way to achieve this without any major ramifications to my code? 有没有办法实现这一点, 而不会对我的代码产生任何重大影响?

I didn't try it, but I think it has to be something like this... (among other solutions) 我没有尝试过,但我认为必须是这样的......(以及其他解决方案)

var oldscrollHeight = $("#chat")[0].scrollHeight;
                      //Takes the height BEFORE reload the div

$.ajax({
  url: "msg-handle/get-messages.php",
  cache: false,
  data: { room: $("#room").val() },
  success: function(data) { $('#chat').html(data)

    var newscrollHeight = $("#chat")[0].scrollHeight;
                          //Takes the height AFTER reload the div

    if(newscrollHeight > oldscrollHeight){ //COMPARES
        $("#chat").scrollTop($("#chat")[0].scrollHeight); //Scrolls
    }
},
});

I think You have to put a $("#chat").scrollTop($("#chat")[0].scrollHeight); 我想你必须放一个$("#chat").scrollTop($("#chat")[0].scrollHeight); after the first load of the chat.. just an advise. 在第一次加载聊天之后..只是一个建议。

the easiest way would be to let the php script pass a flag when there are new messages in the div. 最简单的方法是让php脚本在div中有新消息时传递一个标志。 you then just have to put in a check condition for the the scrolling. 然后你只需要为滚动设置一个检查条件。

another option would be to compare the number of divs in the new .get() result to the previous one and scroll only if there are more divs present in the current. 另一种选择是将新的.get()结果中的div数与前一个进行比较,并仅在当前存在更多div时滚动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM