简体   繁体   中英

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 ! 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 .

My css class .overflowHidden is add on body and html when burgermenu is open .

    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

.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

When you apply 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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