我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
当前回答
像你一样,我正在构建一个聊天应用程序,并希望最近的消息滚动到视图中。这最终对我很有效:
//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' });
其他回答
更新的方法,适用于所有当前浏览器:
this.scrollIntoView(false);
在我的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)函数将停止计时器以允许手动上下滚动。
Java脚本:
getElementById(‘messages)文件。scrollIntoView(虚假);
滚动到当前内容的最后一行。
有时候最简单的就是最好的解决方案: 我不知道这是否有帮助,它帮助我在我想要的时候滚动它。“y=”越高,滚动越向下,当然“0”表示顶部,例如“1000”可能是底部,“2000”或“3000”等等,这取决于你的页面有多长。 这通常在onclick或onmouseover按钮中起作用。
window.scrollTo(x=0,y=150);
您可以使用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>