当菜单 mobile 打开时,我设法禁用 body 上的滚动,但是当我打开 menu mobile 时,桌面/正文页面总是回到顶部

I manage to disable scroll on body when menu mobile is open , but desktop / body page always going back to the top when i open menu mobile

我设法禁用了 body 上的滚动,没问题,感谢 SO! 但是当我打开我的移动菜单时,body 总是回到顶部。

如果我删除

overflow : hidden

body 不再禁用滚动,但当我打开移动菜单时 body 不会返回顶部。

我的 css class .overflowHidden 被添加到 body 和 html 当 burgermenu 打开时 .

    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");
    };
}

我的cssclass

.overflowHidden {
  overflow: hidden;
  margin: 0;
  touch-action: none;
  -ms-touch-action: none;
  position: fixed;
  height: 100%;
}

感谢您的帮助 PS : 我在 nextJS 不知道它是否重要

当您应用 position : fixed; 然后 return 时,您将重置 body 的位置,因为 fixed 元素不属于页面流量

然后我们必须将其高度从 100% 更改为 100vh,以便元素(在本例中为 body)的高度占据整个屏幕并防止出现任何滚动条,因为我们定义了一个高度。

.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;
}