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

div.scrollTop not working in code, works in console

我有一个 div 和 overflow : auto。当我在我的代码中使用时 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
//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.