我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。

我将所有内容都包装在这个div中:

#scroll {
    height:400px;
    overflow:scroll;
}

是否有一种方法来保持它滚动到底部默认使用JS?

有办法保持它滚动到ajax请求后的底部吗?


当前回答

我知道这是一个老问题,但这些解决方案对我都不起作用。我最终使用offset()。顶部得到想要的结果。以下是我在聊天应用程序中轻轻向下滚动屏幕到最后一条消息的方法:

$("#html, body").stop().animate({
     scrollTop: $("#last-message").offset().top
}, 2000);

我希望这能帮助到其他人。

其他回答

这将允许您根据文档高度向下滚动

$('html, body').animate({scrollTop:$(document).height()}, 1000);

我发现这真的很有用,谢谢。

对于Angular 1。在座的X位朋友:

angular.module('myApp').controller('myController', ['$scope', '$document',
  function($scope, $document) {

    var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');
    overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;

  }
]);

只是因为在jQuery元素和HTML DOM元素中包装有点让人困惑。

同样对于聊天应用程序,我发现在你的聊天加载后进行分配是有用的,你也可能需要在短的超时。

像你一样,我正在构建一个聊天应用程序,并希望最近的消息滚动到视图中。这最终对我很有效:

//get the div that contains all the messages
let div = document.getElementById('message-container');

//make the last element (a message) to scroll into view, smoothly!
div.lastElementChild.scrollIntoView({ behavior: 'smooth' });

使用:

var element= $('element');
var maxScrollTop = element[0].scrollHeight - element.outerHeight();
element.scrollTop(maxScrollTop);

或检查滚动到底部:

    var element = $(element);
    var maxScrollTop = element[0].scrollHeight - element.outerHeight();
    element.on('scroll', function() {
        if ( element.scrollTop() >= maxScrollTop ) {
            alert('scroll to bottom');
        }
    });

我也遇到过同样的问题,但有一个额外的限制:我无法控制向滚动容器追加新元素的代码。我在这里找到的例子都不允许我这样做。这是我最终得到的解决方案。

它使用Mutation observer (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver),这使得它只能在现代浏览器上使用(尽管存在填充程序)

所以基本上代码就是这样做的:

var scrollContainer = document.getElementById("myId");

// Define the Mutation Observer
var observer = new MutationObserver(function(mutations) {

  // Compute sum of the heights of added Nodes
  var newNodesHeight = mutations.reduce(function(sum, mutation) {
      return sum + [].slice.call(mutation.addedNodes)
        .map(function (node) { return node.scrollHeight || 0; })
        .reduce(function(sum, height) {return sum + height});
  }, 0);

  // Scroll to bottom if it was already scrolled to bottom
  if (scrollContainer.clientHeight + scrollContainer.scrollTop + newNodesHeight + 10 >= scrollContainer.scrollHeight) {
    scrollContainer.scrollTop = scrollContainer.scrollHeight;
  }

});

// Observe the DOM Element
observer.observe(scrollContainer, {childList: true});

我做了一把小提琴来演示这个概念: https://jsfiddle.net/j17r4bnk/