如何始终滚动到底部?
我想要滚动向下滚动到底部添加一些文本到div。 这是我的代码。我找不到为什么它不起作用。如何始终滚动到底部?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onload =() => {
const add = document.getElementById('add');
const c = document.getElementById('content');
add.addEventListener('click',() => {
c.innerHTML += '<p>aaaaa</p>';
c.scrollTop = c.scrollHeight;
});
};
</script>
</head>
<body>
<button id="add">add</button>
<div id="content">
</div>
</body>
</html>
我建议使用scrollIntoView
方法。
因此,而不是c.scrollTop = c.scrollHeight;
只是做c.scrollIntoView(false);
。
您尝试的解决方案(c.scrollTop = c.scrollHeight;
)不起作用,因为您将元素动态添加到div中。我的意思是这样的解决方案是一次性交易。如果您更改内容,则必须重新执行滚动。
除此之外,你可以使用window.scrollTo
方法做以下伎俩:
window.scrollTo(0, c.scrollHeight);
如果你想向下滚动,您必须使用此:
window.scrollTo(0,c.scrollHeight);
你的意思是使用'window.scrollTo(c.scrollHeight,0);'而不是'c.scrollTop = c.scrollHeight;'? – user3130007
是的,我认为这将工作 –
@ user3130007我相信,他的意思是。但反过来也应该传递参数:'window.scrollTo(0,c.scrollHeight);' –
使用scrollIntoView()
而不是scrollTop
& scrollHeight
并且不要忘记固定按钮的位置,否则它将不断地向上滚动以继续。
感谢您的提示 – user3130007
'c.scrollIntoView(false);'它运作良好。 – user3130007
@ user3130007是的,它非常有用。 –