如何在添加数据时自动滚动到div的结尾? [英] How to auto-scroll to end of div when data is added?
问题描述
我在 div
里面有一个表
,其格式如下:
I have a table
inside of a div
with the following style:
#data {
overflow-x:hidden;
overflow-y:visible;
height:500px;
}
一旦将足够的数据添加到表中,这将显示一个垂直滚动条。但是,当添加新数据时,我想要 div
元素自动滚动到底部。
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.
JavaScript代码可以使用吗?
What JavaScript code could I use to do so? I am open to options in JQuery if necessary but would prefer a JavaScript solution.
推荐答案
如果你不知道什么时候数据会添加到 #data
,您可以设置一个间隔,将元素的scrollTop更新为其scrollHeight每几秒钟。如果您在控制数据添加时,只需在添加数据后调用以下函数的内部。
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.
window.setInterval(function() {
var elem = document.getElementById('data');
elem.scrollTop = elem.scrollHeight;
}, 5000);
这篇关于如何在添加数据时自动滚动到div的结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!