Javascript 添加数据时如何自动滚动到div的末尾?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7303948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to auto-scroll to end of div when data is added?
提问by Drew Galbraith
I have a table
inside of a div
with the following style:
我有一个table
的内部div
具有以下样式:
#data {
overflow-x:hidden;
overflow-y:visible;
height:500px;
}
This displays a vertical scroll bar once enough data is added to the table. However, when new data is added I would like the div
element to auto-scroll to the bottom.
一旦将足够的数据添加到表中,就会显示一个垂直滚动条。但是,当添加新数据时,我希望div
元素自动滚动到底部。
What JavaScript code could I use to do so? I am open to options in JQuery if necessary but would prefer a JavaScript solution.
我可以使用哪些 JavaScript 代码来做到这一点?如有必要,我对 JQuery 中的选项持开放态度,但更喜欢 JavaScript 解决方案。
回答by VNO
If you don't know when data will be added to #data
, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.
如果您不知道何时将数据添加到#data
,您可以设置一个间隔,每隔几秒将元素的 scrollTop 更新为其 scrollHeight。如果您控制何时添加数据,只需在添加数据后调用以下函数的内部即可。
window.setInterval(function() {
var elem = document.getElementById('data');
elem.scrollTop = elem.scrollHeight;
}, 5000);
回答by Valamas
var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;