Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - 如何在添加数据时自动滚动到div的结尾? [重复](How to auto-scroll to end of div when data is added? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

I have a table inside of a div with the following style:

(我在div有一个table ,具有以下样式:)

#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?

(我可以使用哪些JavaScript代码?)

I am open to options in JQuery if necessary but would prefer a JavaScript solution.

(如果有必要,我愿意接受JQuery中的选项,但更喜欢JavaScript解决方案。)

  ask by Drew Galbraith translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(如果您不知道何时将数据添加到#data ,您可以设置一个间隔,以便每隔几秒钟将元素的scrollTop更新为其scrollHeight。)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...