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

标签 javascript scrolltop

我有一个具有设定高度和溢出:自动的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/

相关文章:

javascript - Window 与 document.documentElement 最佳实践

javascript - 无法让最基本的点击事件绑定(bind)起作用

javascript - 防止底层div的onclick事件触发

javascript - jquery 中 val() 的作用是什么?

javascript - 当在选项上设置 header 时,获取 POST 内容类型不会更改

javascript - 如何在页面加载事件之后立即获得页面的 scrollTop?

javascript - $(window).scrollTop() 与 $(document).scrollTop()

javascript - Highchart 绘图点显示不正确

javascript - ScrollTop 到元素 - 20px

javascript - jquery的scrolltop和scrollleft工作得很好,但是在iphone上它们都将另一个栏滚动到它的起始位置?