我有一个具有设定高度和溢出:自动
的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
最佳答案
//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.
关于javascript - div.scrollTop 不在代码中工作,在控制台中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30435847/