div.scrollTop无法在代码中工作,在控制台中工作

时间:2015-05-25 10:08:19

标签: javascript scrolltop

我有一个设定高度为overflow : auto的div。当我在我的代码div.scrollTop = 0;中使用它时它不起作用,但如果我在控制台中执行相同的操作,它就会起作用。

//here, div is scrolled half way
div.innerHTML = "";
div.scrollTop = 0;  //not working
div.appendChild(new_long_content); 
//here, div is still scrolled

1 个答案:

答案 0 :(得分:0)

//assume we have a `div` with a lot of content and a scrollbar, 
//and the content is scrolled down:

//this case works
div.innerHTML = ""; //content is small, the scrollbar will disappear.
div.appendChild(new_long_content);  //scrollbar reappears and it will have the 
                                    //same position as it had before disappearing: 0.
div.scrollTop = 0;  //px - new content is scrolled up.

//this doesn't work
div.innerHTML = "";  //content is very short so the scrollbar will disappear.
div.scrollTop = 0;   //px - setting scrollTop when scrollbar not in use has no effect.
div.appendChild(new_long_content); //new content is added, scrollbar appears again, 
                                   //but with the old scroll position.

//summary: you should only use scrollTop when scrollbar is visible and after 
//the new content is loaded, because scrollTop affects only the scrollbar directly and the div only indirectly.