首页 > 解决方案 > Load div each x second and allow scroll top

问题描述

In a chat application I would like to keep loading the div that receives the messaged posted and scroll down to the div. My issue is once the scroll down is made I cannot scroll to the top to see previous messages because the scroll down is in the setInterval function. How can I solve this or is there another way to achieve this ?

Fiddle : jsfiddle.net/hu4zqq4x/316

Thanks

setInterval(function() {
  $(".messages").stop().animate({
    scrollTop: $(".messages")[0].scrollHeight
  }, 1000);
  var messageTo = $("#message-to").val();
  var message_from = <?=$iduser?>;
  $('#new_message1_doc').load("<?php echo base_url("
    admin_medico / newMessageDoc ")?>?messageTo=" + messageTo + "&id_user=" + message_from);
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='messages'>
  <div id="new_message1_doc"></div>
</div>

标签: jqueryhtml

解决方案


您可以保存滚动到的位置,如果没有新消息,则该位置不会更改,在这种情况下,请不要执行滚动。

这里的例子

var lastScrollPosition;
function getMessages(letter) {
    var div = $("#messages");
    if (lastScrollPosition != div.prop('scrollHeight')){
      lastScrollPosition = div.prop('scrollHeight');
      div.scrollTop(lastScrollPosition );
    }
}

$(function() {
setInterval(function(){
     getMessages();
}, 1000);

});

另一种方法是仅发送新消息,然后仅在新消息到达时滚动。


推荐阅读