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

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

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

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

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


当前回答

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

它使用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 objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;

如果你使用jQuery scrollTop,这就简单多了:

$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);

有时候最简单的就是最好的解决方案: 我不知道这是否有帮助,它帮助我在我想要的时候滚动它。“y=”越高,滚动越向下,当然“0”表示顶部,例如“1000”可能是底部,“2000”或“3000”等等,这取决于你的页面有多长。 这通常在onclick或onmouseover按钮中起作用。

window.scrollTo(x=0,y=150);

使用jQuery动画:

$('#DebugContainer').stop().animate({
  scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);

您可以使用Element.scrollTo()方法。

它可以使用内置的浏览器/操作系统动画,所以它非常流畅。

function scrollToBottom() { const scrollContainer = document.getElementById('container'); scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, left: 0, behavior: 'smooth' }); } // initialize dummy content const scrollContainer = document.getElementById('container'); const numCards = 100; let contentInnerHtml = ''; for (let i=0; i<numCards; i++) { contentInnerHtml += `<div class="card mb-2"><div class="card-body">Card ${i + 1}</div></div>`; } scrollContainer.innerHTML = contentInnerHtml; .overflow-y-scroll { overflow-y: scroll; } <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet"/> <div class="d-flex flex-column vh-100"> <div id="container" class="overflow-y-scroll flex-grow-1"></div> <div> <button class="btn btn-primary" onclick="scrollToBottom()">Scroll to bottom</button> </div> </div>