[英]Prevent scrolling when mobile nav menu is open?
我有一个从汉堡打开的简单导航菜单。 虽然这是打开的,但如何防止屏幕上的所有滚动? 导航栏是 100vh,我想防止在它打开时滚动过去?
到目前为止导航菜单的 Js(没有滚动)
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()
菜单打开时添加overflow-y: hidden
到body
元素,关闭菜单时将其移除。
打开时:
document.body.style.overflowY = 'hidden';
关闭时:
document.body.style.overflowY = 'visible';
编辑:
您可以使用上面的示例,例如:
document.body.style.overflowY = document.body.style.overflowY === 'hidden' ? 'visible' : 'hidden'; // if current styling is *hidden* then change to visible, otherwise change to hidden
当您为导航栏切换 class 时,我认为您也更容易为body
元素切换 class。 因此,您可以将以下代码添加到您的项目中:
burger.addEventListener('click', () => {
document.body.classList.toggle('no-scroll')
nav.class...
})
并创建一个名为no-scroll
的 CSS class :
.no-scroll {
overflow-y: hidden;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.