最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent scrolling when mobile nav menu is open? - Stack Overflow

programmeradmin0浏览0评论

I have a simple nav menu opened from a burger. Whilst this is open how can I prevent all scrolling on the screen? The nav bar is 100vh and I want to prevent scrolling past it whilst it is open?

Js for the nav menu so far (nothing for scrolling)

const navSlide = () => {
    const burger = document.getElementById('burger')
    const nav = document.getElementById('nav')
    const navLinks = document.querySelectorAll('.nav-links li')
    
    burger.addEventListener('click', () => {
        nav.classList.toggle('nav-active')
        navLinks.forEach( (link, index) => {
            if (link.style.animation) {
                link.style.animation = ''
            } else {
                link.style.animation = `navLinkFade 0.7s ease forwards ${index / 7 + 0.4}s`
                }
    })
    burger.classList.toggle('toggle')
  })
}

navSlide()

I have a simple nav menu opened from a burger. Whilst this is open how can I prevent all scrolling on the screen? The nav bar is 100vh and I want to prevent scrolling past it whilst it is open?

Js for the nav menu so far (nothing for scrolling)

const navSlide = () => {
    const burger = document.getElementById('burger')
    const nav = document.getElementById('nav')
    const navLinks = document.querySelectorAll('.nav-links li')
    
    burger.addEventListener('click', () => {
        nav.classList.toggle('nav-active')
        navLinks.forEach( (link, index) => {
            if (link.style.animation) {
                link.style.animation = ''
            } else {
                link.style.animation = `navLinkFade 0.7s ease forwards ${index / 7 + 0.4}s`
                }
    })
    burger.classList.toggle('toggle')
  })
}

navSlide()
Share Improve this question asked Feb 18, 2021 at 11:21 Dan WilstropDan Wilstrop 4451 gold badge5 silver badges15 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Add overflow-y: hidden to the body element when the menu is open and remove it when you close the menu.

When opening:

document.body.style.overflowY = 'hidden';

When closing:

document.body.style.overflowY = 'visible';

EDIT:

You can use the above examples like:

document.body.style.overflowY = document.body.style.overflowY === 'hidden' ? 'visible' : 'hidden'; // if current styling is *hidden* then change to visible, otherwise change to hidden

As you are toggling the class for the navbar, I think it would be easier for you to toggle a class for the body element too. So you can add following code to your project:

burger.addEventListener('click', () => {
  document.body.classList.toggle('no-scroll')
  nav.class...
})

And create a CSS class named no-scroll:

.no-scroll {
  overflow-y: hidden;
}
发布评论

评论列表(0)

  1. 暂无评论