通过使用requestAnimationFrame(),滚动条会在DOM重绘时得到精确刷新:
function scrollRefresh(element) {
// initial overflow attribute
element.style.overflow = "auto";
requestAnimationFrame(() => {
// final overflow attribute
element.style.overflow = "overlay";
});
}
一个强制DOM刷新滚动条的函数将会起作用:
function scrollRefresh(element) {
// initial overflow attribute
element.style.overflow = "auto";
setTimeout(() => {
// final overflow attribute
element.style.overflow = "overlay";
}, 17); // 17 ms timeout
}
这个解决方案有两点需要注意:
auto
溢出属性。以auto
或overlay
开头并不重要,但是最终溢出属性与初始属性不同是必要的。0毫秒
的超时时间不起作用,而5毫秒
的超时时间可以达到约30%的成功率。20毫秒
的超时时间对我来说一直有效。我认为超时时间与DOM刷新率有关。从快速搜索中得知,它大约是60 fps
(或16.6̅毫秒
),因此20毫秒
已经足够了。17毫秒
的超时时间应该足够缓慢,以使DOM始终呈现溢出更改。
这里有一个演示函数的工作方式:
我想感谢@lastr2d2的评论,因为它帮助我找到了解决方案。
::-webkit-scrollbar{ display:none; }
创建一个不可见的滚动条。 - lastr2d2