移动端菜单展开后滚动问题:导航栏仍移动,需禁用页面滚动
Hey there! I've run into this exact mobile menu problem before — super annoying when users can scroll the page behind an open menu, right? Let's get this fixed up for you.
Step 1: Add CSS to Disable Scrolling
First, we'll create a CSS class that locks the body from scrolling. This works across most mobile browsers, including tricky ones like iOS Safari:
.body-no-scroll { overflow: hidden; position: fixed; width: 100%; }
The position: fixed ensures the page stays in place even if overflow: hidden doesn't catch it on some devices.
Step 2: Update Your jQuery Code
We need to toggle this scroll-lock class on the body whenever the menu is opened/closed, and also tweak the scroll handler to ignore navigation changes when the menu is open.
Quick heads up: I noticed you used $("menu") in your code — make sure that selector matches your actual menu trigger (like a class .menu or ID #menu; otherwise the click event won't fire!)
Here's the updated code:
$(document).ready(function(){ // Replace .menu with your actual menu trigger selector $(".menu").click(function(){ $("nav").slideToggle(800, function() { // Toggle the scroll-lock class after the menu animation finishes $("body").toggleClass("body-no-scroll"); }); }); $(window).scroll(function() { var distanceFromTop = $(document).scrollTop(); // Only adjust the nav's fixed class if the menu is NOT open if (!$("nav").is(":visible")) { if (distanceFromTop >= $('.banner').height()) { $('nav').addClass('fixed'); } else { $('nav').removeClass('fixed'); } } }); });
How This Works
- When the menu is clicked, we toggle the navigation's visibility and flip the
body-no-scrollclass to lock/unlock page scrolling. Using the slideToggle callback ensures the scroll lock happens right when the menu animation completes. - We added a check in the scroll handler so the navigation's
fixedclass only updates when the menu is closed — this prevents the nav from shifting around while the menu is open.
Extra Tips
- Test this on a real mobile device (or use Chrome's Device Toolbar) to make sure it works smoothly across different browsers.
- If your open menu uses a fixed position itself, you might want to adjust its z-index to ensure it stays above everything else while open.
内容的提问来源于stack exchange,提问作者Mab

