我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。
我将所有内容都包装在这个div中:
#scroll {
height:400px;
overflow:scroll;
}
是否有一种方法来保持它滚动到底部默认使用JS?
有办法保持它滚动到ajax请求后的底部吗?
当前回答
你可以像这样使用HTML DOM scrollIntoView方法:
var element = document.getElementById("scroll");
element.scrollIntoView();
其他回答
平滑滚动Javascript:
. getelementbyid(“信息”)。scrollIntoView({behavior: 'smooth', block: 'end'});
如果你使用jQuery scrollTop,这就简单多了:
$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
你可以像这样使用HTML DOM scrollIntoView方法:
var element = document.getElementById("scroll");
element.scrollIntoView();
我发现这真的很有用,谢谢。
对于Angular 1。在座的X位朋友:
angular.module('myApp').controller('myController', ['$scope', '$document',
function($scope, $document) {
var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');
overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;
}
]);
只是因为在jQuery元素和HTML DOM元素中包装有点让人困惑。
同样对于聊天应用程序,我发现在你的聊天加载后进行分配是有用的,你也可能需要在短的超时。
像你一样,我正在构建一个聊天应用程序,并希望最近的消息滚动到视图中。这最终对我很有效:
//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' });