You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移动端菜单展开后滚动问题:导航栏仍移动,需禁用页面滚动

Fixing Mobile Menu Scroll Issue: Disable Page Scrolling When Menu is Open

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-scroll class 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 fixed class 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:01:25