JQuery - 除非用户向上滚动,否则滚动并锚定到ajax驱动的div的底部

Dam*_*ien 5 html javascript ajax jquery

我试图滚动到div的底部,#chat-feed溢出设置为auto并保持在那里,除非用户滚动该div的内容.如果它们向下滚动,则div应锁定到底部,新内容将显示在底部.

已知问题:我已尝试使用我的代码实现此答案,但我还不了解Javascript以使其正常工作.如果来自chat-feed.php容器的内容高于容器,则滚动停留在顶部.似乎给出的答案不尊重从外部文件加载的内容.

关键的事情:新内容应该显示在底部,div应该在新内容加载时滚动到底部,除非用户已经向上滚动了一点.如果用户向下滚动,则它应锁定到底部,新内容将显示在底部并可见.

<div id="chat-feed" style="height: 200px; width: 300px; overflow: auto;"></div>


<script>
$(document).ready(function(){
    setInterval(function(){
        $('#chat-feed').load("chat-feed.php").fadeIn("slow");
    }, 1000);
});
</script>
Run Code Online (Sandbox Code Playgroud)

演示链接

K S*_*ett 1

关于您链接的问题,有一个更好的实现/sf/answers/1474720201/

我修改了该作者的代码如下:

$(document).ready(function() {

  var out = document.getElementById("chat-feed"); // outer container of messages
  var c = 0; // used only to make the fake messages different

  // generate some chatter every second
  setInterval(function() {

    //check current scroll position BEFORE message is appended to the container
    var isScrolledToBottom = checkIfScrolledBottom();

    // append new mesage here
    $('#chat-feed').append("<div>Some new chat..." + c++ + "</div>").fadeIn("slow");

    // scroll to bottom if scroll position had been at bottom prior
    scrollToBottom(isScrolledToBottom);

  }, 1000);

  function checkIfScrolledBottom() {
    // allow for 1px inaccuracy by adding 1
    return out.scrollHeight - out.clientHeight <= out.scrollTop + 1;
  }

  function scrollToBottom(scrollDown) {
    if (scrollDown)
      out.scrollTop = out.scrollHeight - out.clientHeight;
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="chat-feed" style="height: 150px; width: 300px; overflow: auto;"></div>
Run Code Online (Sandbox Code Playgroud)

更新

JQuery 的.load()函数删除关联元素 ( chat-feed) 并重新添加。这意味着该out变量指向旧的已删除元素,而不是新的。解决方案是out在执行后更新变量.load()

$('#chat-feed').load("chat-feed.php").fadeIn("slow");
out = document.getElementById("chat-feed"); // outer container of messages
Run Code Online (Sandbox Code Playgroud)