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

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

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

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

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


当前回答

我的场景:我有一个字符串列表,我必须在其中添加用户给定的字符串,并自动滚动到列表的末尾。我已经固定了列表显示的高度,在此之后它应该溢出。

我试过@Jeremy Ruten的答案,它工作,但它滚动到(n-1)个元素。如果有人面临这种类型的问题,可以使用setTimeOut()方法解决。你需要修改代码如下:

setTimeout(() => {
    var objDiv = document.getElementById('div_id');
    objDiv.scrollTop = objDiv.scrollHeight
}, 0)

下面是我创建的StcakBlitz链接,其中显示了问题及其解决方案:https://stackblitz.com/edit/angular-ivy-x9esw8

其他回答

如果您的项目针对现代浏览器,您现在可以使用CSS Scroll Snap来控制滚动行为,例如将任何动态生成的元素保持在底部。

.wrapper > div { background-color: white; border-radius: 5px; padding: 5px 10px; text-align: center; font-family: system-ui, sans-serif; } .wrapper { display: flex; padding: 5px; background-color: #ccc; border-radius: 5px; flex-direction: column; gap: 5px; margin: 10px; max-height: 150px; /* Control snap from here */ overflow-y: auto; overscroll-behavior-y: contain; scroll-snap-type: y mandatory; } .wrapper > div:last-child { scroll-snap-align: start; } <div class="wrapper"> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> <div>07</div> <div>08</div> <div>09</div> <div>10</div> </div>

在我的Angular 6应用中,我这样做了:

postMessage() {
  // post functions here
  let history = document.getElementById('history')
  let interval    
  interval = setInterval(function() {
    history.scrollTop = history.scrollHeight
    clearInterval(interval)
  }, 1)
}

clearInterval(interval)函数将停止计时器以允许手动上下滚动。

使用jQuery动画:

$('#DebugContainer').stop().animate({
  scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);
var mydiv = $("#scroll");
mydiv.scrollTop(mydiv.prop("scrollHeight"));

来自jQuery 1.6的工作

https://api.jquery.com/scrollTop/

http://api.jquery.com/prop/

您可以使用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>