var element = document.getElementById("yourDivID");
element.scrollTop = element.scrollHeight;
[编辑],为了匹配注释…
function updateScroll(){
var element = document.getElementById("yourDivID");
element.scrollTop = element.scrollHeight;
}
每当添加内容时,调用函数updateScroll(),或设置一个计时器:
//once a second
setInterval(updateScroll,1000);
如果你只想在用户没有移动的情况下更新:
var scrolled = false;
function updateScroll(){
if(!scrolled){
var element = document.getElementById("yourDivID");
element.scrollTop = element.scrollHeight;
}
}
$("#yourDivID").on('scroll', function(){
scrolled=true;
});
const out = document.getElementById("out")
let c = 0
setInterval(function() {
// allow 1px inaccuracy by adding 1
const isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1
const newElement = document.createElement("div")
newElement.textContent = format(c++, 'Bottom position:', out.scrollHeight - out.clientHeight, 'Scroll position:', out.scrollTop)
out.appendChild(newElement)
// scroll to bottom if isScrolledToBottom is true
if (isScrolledToBottom) {
out.scrollTop = out.scrollHeight - out.clientHeight
}
}, 500)
function format () {
return Array.prototype.slice.call(arguments).join(' ')
}
#out {
height: 100px;
}
<div id="out" style="overflow:auto"></div>
<p>To be clear: We want the scrollbar to stick to the bottom if we have scrolled all the way down. If we scroll up, then we don't want the content to move.
</p>
//Make sure message list is scrolled to the bottom
var container = $('#MessageWindowContent')[0];
var containerHeight = container.clientHeight;
var contentHeight = container.scrollHeight;
container.scrollTop = contentHeight - containerHeight;
$(function(){
var isScrolledToBottom = false;
// Now let's load our messages
function load_messages(){
$( "#chatscreen" ).append( "<br>Test" );
updateScr();
}
var out = document.getElementById("chatscreen");
var c = 0;
$("#chatscreen").on('scroll', function(){
console.log(out.scrollHeight);
isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 10;
});
function updateScr() {
// allow 1px inaccuracy by adding 1
//console.log(out.scrollHeight - out.clientHeight, out.scrollTop + 1);
var newElement = document.createElement("div");
newElement.innerHTML = c++;
out.appendChild(newElement);
console.log(isScrolledToBottom);
// scroll to bottom if isScrolledToBotto
if(isScrolledToBottom) {out.scrollTop = out.scrollHeight - out.clientHeight; }
}
var add = setInterval(updateScr, 1000);
setInterval(load_messages,300); // change to 300 to show the latest message you sent after pressing enter // comment this line and it works, uncomment and it fails
// leaving it on 1000 shows the second to last message
setInterval(updateScroll,30);
});
let div = document.querySelector('div.scrollableBox');
let span = document.createElement('span');
span.textContent = 'Hello';
let divCurrentUserScrollPosition = div.scrollTop + div.offsetHeight;
let divScrollHeight = div.scrollHeight;
// We have the current scroll positions saved in
// variables, so now we can append the new element.
div.append(span);
if ((divScrollHeight === divCurrentUserScrollPosition)) {
// Scroll to bottom of div
div.scrollTo({ left: 0, top: div.scrollHeight });
}
这是我的完整的示例。在我实际的应用程序中,有其他两个类mh-100 col overflow-auto的第三列,不需要内部行/列,因为没有标题贴在顶部(如果视口太小,它只会正常滚动)。列表有一个ID,我用来选择和添加到它们前面或删除顶部元素(这是反向列表的底部<li>项)。
这里提供了一个较小的版本:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="vh-100 w-75 container-fluid">
<h1>2nd Level Scrolling Example</h1>
<div class="h-75 row align-items-end">
<div class="mh-100 col d-flex flex-column">
<div class="row align-items-end">
<div class="col"><h3>Normal scroll list, grow on top</h3></div>
</div>
<div class="row align-items-end overflow-auto">
<div class="mh-100 col">
<ul class="list-group">
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ut</li>
<li>tortor eu ex tincidunt pretium non eu nisl. Ut eu libero ac velit</li>
<li>ultricies dapibus. Donec id augue scelerisque, gravida est ut,</li>
<li>commodo sapien. Interdum et malesuada fames ac ante ipsum primis</li>
<li>in faucibus. Suspendisse volutpat fermentum finibus. Cras egestas</li>
<li>tempor tempor. Suspendisse potenti. Mauris ac tellus ultrices lectus</li>
<li>accumsan pellentesque. Nullam semper, nisi nec euismod ultrices, leo</li>
<li>sem bibendum sapien, in rutrum sapien massa id mi.</li>
</ul>
</div>
</div>
</div>
<div class="mh-100 col d-flex flex-column">
<div class="row align-items-end">
<div class="col"><h3>Reverse scroll list, grow on bottom</h3></div>
</div>
<div class="row align-items-end d-flex flex-column-reverse overflow-auto">
<div class="mh-100 col">
<ul class="list-group">
<li>sem bibendum sapien, in rutrum sapien massa id mi.</li>
<li>accumsan pellentesque. Nullam semper, nisi nec euismod ultrices, leo</li>
<li>tempor tempor. Suspendisse potenti. Mauris ac tellus ultrices lectus</li>
<li>in faucibus. Suspendisse volutpat fermentum finibus. Cras egestas</li>
<li>commodo sapien. Interdum et malesuada fames ac ante ipsum primis</li>
<li>ultricies dapibus. Donec id augue scelerisque, gravida est ut,</li>
<li>tortor eu ex tincidunt pretium non eu nisl. Ut eu libero ac velit</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ut</li>
</ul>
</div>
</div>
</div>
</div>
</div>
// just to add some numbers, so we can see the effect
// the actual solution requires no javascript
let num = 1001;
const container = document.getElementById("scroll-container");
document.getElementById("adder").onclick = () =>
container.append(
Object.assign(document.createElement("div"), {
textContent: num++
})
);