我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
当前回答
在我的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)函数将停止计时器以允许手动上下滚动。
其他回答
我也遇到过同样的问题,但有一个额外的限制:我无法控制向滚动容器追加新元素的代码。我在这里找到的例子都不允许我这样做。这是我最终得到的解决方案。
它使用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/
试试下面的代码:
const scrollToBottom = (id) => {
const element = document.getElementById(id);
element.scrollTop = element.scrollHeight;
}
你也可以使用Jquery使滚动平滑:
const scrollSmoothlyToBottom = (id) => {
const element = $(`#${id}`);
element.animate({
scrollTop: element.prop("scrollHeight")
}, 500);
}
下面是演示
下面是它的工作原理:
参考:scrollTop, scrollHeight, clientHeight
更新的方法,适用于所有当前浏览器:
this.scrollIntoView(false);
可选择的解决方案
function scrollToBottom(element) {
element.scroll({ top: element.scrollHeight, behavior: 'smooth' });
}
我的场景:我有一个字符串列表,我必须在其中添加用户给定的字符串,并自动滚动到列表的末尾。我已经固定了列表显示的高度,在此之后它应该溢出。
我试过@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