简体   繁体   English

当移动菜单打开时,我设法禁用了身体滚动,但是当我打开移动菜单时,桌面/正文页面总是回到顶部

[英]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

I'm manage to disable scroll on body , no problem with that , thanks to SO !我设法在身体上禁用滚动,没问题,多亏了 SO! But when i open my mobile menu , body always going back to the top .但是当我打开我的移动菜单时,身体总是回到顶部。

If i remove如果我删除

overflow : hidden溢出:隐藏

Scroll isn't anymore disable on body , but body doesn't going back to the top when i open my mobile menu .滚动不再在 body 上禁用,但是当我打开我的移动菜单时,body 不会回到顶部。

My css class .overflowHidden is add on body and html when burgermenu is open .当 burgermenu 打开时,我的 css 类 .overflowHidden 被添加到 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");
    };
}

my css class我的 CSS 类

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

Thanks for your help PS : i'm on nextJS don't know if it's important感谢您的帮助 PS:我在 nextJS 不知道这是否重要

When you apply position : fixed;申请position : fixed; and then return you will reset the position of your body because a fixed element isn't part of the page's flow然后返回您将重置身体的位置,因为固定元素不是页面流的一部分

We must then change it's height from 100% to 100vh so the element's (in this case the body) height takes the whole screen and prevent any scrollbar to appear since we defined a height.然后我们必须将它的高度从 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM