Chat does not scroll to the bottom when I use Jquery Load method

て烟熏妆下的殇ゞ 提交于 2019-12-24 16:06:39

问题


Chat does not scroll to bottom after jquery load method

My chat works by load new messages inside a scrolling div with jquery load method but div do not scroll to bottom when new messages are loaded, also I can't run out.scrollTop = out.scrollHeight; with the div load because as it loads every second when user click scroll to older messages it just make the scroll control flash all the time.

I am using this example of this fiddle http://jsfiddle.net/dotnetCarpenter/KpM5j/ It all looks to work fine but it's not working when I use with jquery .load() method my index.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>

<script>
  setInterval(
    function() {
      $('#out').load('load_chat.php');
      var messageBody = document.querySelector('#out');
      out.scrollTop = out.scrollHeight - out.clientHeight;
    }, 3000);
</script>

<script>
  var out = document.getElementById("out");
  var c = 0;
  var add = setInterval(function() {
    // allow 1px inaccuracy by adding 1
    var isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1;
    console.log(out.scrollHeight - out.clientHeight, out.scrollTop + 1);
    var newElement = document.createElement("div");
    newElement.innerHTML = c++;
    out.appendChild(newElement);
    // scroll to bottom if isScrolledToBotto
    if (isScrolledToBottom)
      out.scrollTop = out.scrollHeight - out.clientHeight;
  }, 1000);
</script>

<div id="out" style="overflow-y: scroll; height:80px;"></div>

I need to load the load_chat.php and also keep the page scrolling to the bottom I can't use

var out = document.getElementById('out');
out.scrollTop = out.scrollHeight;

inside the load by Interval function, because it makes scrolling very weird, can someone help?

来源:https://stackoverflow.com/questions/57367962/chat-does-not-scroll-to-the-bottom-when-i-use-jquery-load-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!