多亏了SO,我成功地禁用了主体上的滚动,没有问题!但当我打开手机菜单时,身体总是回到顶部
如果我删除
溢出:隐藏
滚动在body上不再禁用,但当我打开移动菜单时,body不会回到顶部。
我的css类.overlowHidden是在burgermenu打开时添加到body和html中的。
const [showBurgerMenu, setShowBurgerMenu] = useState(false)
const handleOnClick = () => {
const burger = document.querySelector('.burger');
burger.classList.toggle('active');
setShowBurgerMenu(!showBurgerMenu);
if (showBurgerMenu === false) {
document.querySelector("body").classList.add("overflowHidden");
document.querySelector("html").classList.add("overflowHidden")
} else if (showBurgerMenu === true) {
document.querySelector("body").classList.remove("overflowHidden");
document.querySelector("html").classList.remove("overflowHidden");
};
}
我的css类
.overflowHidden {
overflow: hidden;
margin: 0;
touch-action: none;
-ms-touch-action: none;
position: fixed;
height: 100%;
}
谢谢你的帮助PS:我在nextJS上不知道是否重要
当您应用position : fixed;
然后返回时,您将重置身体的位置,因为固定元素不是页面流的一部分
然后,我们必须将它的高度从100%更改为100vh,这样元素(在本例中为主体(的高度就占据了整个屏幕,并防止出现任何滚动条,因为我们定义了高度。
.overflowHidden {
overflow: hidden;
margin: 0;
touch-action: none;
-ms-touch-action: none;
/* position: fixed; we get rid of this line which resets the flow of the page */
/* height: 100%; we change 100% to 100vh */
height: 100vh;
}