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

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

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

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

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


当前回答

你也可以,使用jQuery,附加一个动画到html,文档的主体通过:

$(“html,body”).animate({scrollTop:$(“#div-id”)[0].offsetTop}, 1000);

这将导致一个平滑的滚动到div顶部,id为“div-id”。

其他回答

只是作为一个额外的片段。我正在使用angular,并试图在用户选择与用户的不同对话时将消息线程滚动到底部。为了确保在使用ng-repeat for消息将新数据加载到div之后滚动仍然有效,只需在超时时间内包装滚动片段。

$timeout(function(){
    var messageThread = document.getElementById('message-thread-div-id');
    messageThread.scrollTop = messageThread.scrollHeight;
},0)

这将确保在数据插入DOM之后触发滚动事件。

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

它使用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/

使用:

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');
        }
    });

你也可以,使用jQuery,附加一个动画到html,文档的主体通过:

$(“html,body”).animate({scrollTop:$(“#div-id”)[0].offsetTop}, 1000);

这将导致一个平滑的滚动到div顶部,id为“div-id”。

小附录:仅限滚动,如果最后一行已经可见。如果滚动一点点,将内容留在原地(注意:没有测试过不同的字体大小。这可能需要在">= compare "中进行一些调整):

var objDiv = document.getElementById(id);
var doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight);                   

// add new content to div
$('#' + id ).append("new line at end<br>"); // this is jquery!

// doScroll is true, if we the bottom line is already visible
if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;