在Next Js中设置body.overflow隐藏后无法冻结滚动

问题描述 投票:0回答:1

我在我的 Nextjs 中遇到这个问题,即使我将

document.body.style.overflow
设置为
hidden
后我也无法冻结页面滚动。

这是代码: https://codesandbox.io/p/sandbox/gallant-leavitt-i0fz2c?file=%2Fpages%2Findex.tsx&selection=%5B%7B%22endColumn%22%3A28%2C%22endLineNumber%22%3A13%2C%22startColumn %22%3A27%2C%22startLineNumber%22%3A13%7D%5D

如你所见: 在第 11-14 行中,我单击了冻结按钮,它禁用了滚动。 enter image description here

结果: 页面仍然可以滚动。

请告诉我解决方案。

javascript reactjs dom next.js frontend
1个回答
0
投票

除了

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;`;
© www.soinside.com 2019 - 2024. All rights reserved.