我在我的 Nextjs 中遇到这个问题,即使我将
document.body.style.overflow
设置为 hidden
后我也无法冻结页面滚动。
如你所见: 在第 11-14 行中,我单击了冻结按钮,它禁用了滚动。
结果: 页面仍然可以滚动。
请告诉我解决方案。
除了
position:fixed
之外还需要加上
overflow:hidden
document.body.style.cssText = "overflow: hidden; position:fixed;";
防止滚动会丢失滚动位置。因此,当重新启用滚动时,它会将滚动位置重置为页面顶部,而不是用户离开的位置。为了防止这种情况,您需要设置 scrollTop 位置。
const scrollTop = (document.documentElement || document.body).scrollTop;
document.body.style.cssText = `overflow: hidden; position:fixed; margin-top: -${scrollTop}px;`;