打开全屏菜单时禁用页面滚动的技术实现问询
解决全屏菜单打开时禁用页面滚动的方案
核心思路是借助已有的toggle逻辑,在菜单打开时给body添加禁止滚动的样式类,关闭时移除该类,确保菜单显示期间用户无法滚动页面。
修改后的完整代码
JavaScript
var menuAnimation = gsap.timeline({paused:true}); var menuAnimationBack = gsap.timeline({paused:true, reversed: true}); var navMain = document.getElementById("nav-main"); var menuButton = document.getElementById("menu-button"); var toggle = true; gsap.set('.link',{y:30}); menuAnimation .to(navMain, {duration:.8, width: '100%', clipPath: "polygon(0 0, 100% 0, 100% 100%, 0 100%)", ease: "power2.inOut", x:0, y:0, z:0}) .to('.link',{duration:.5,autoAlpha:1,y:0,stagger:.2,ease: "power4.out"}); menuAnimationBack .to('.link',{duration:.5,autoAlpha:0,y:30,stagger:.2,ease: "power4.out"}) .to(navMain, {duration:0.55,width: 0, clipPath: "polygon(0 0, -100% 0, 100% 100%, 0 100%)", ease: "power4.in", x:0, y:0, z:0}); menuButton.onclick = function() { toggle = !toggle; // 同步控制页面滚动 if (!toggle) { menuAnimation.play(0); document.body.classList.add('no-scroll'); } else { menuAnimationBack.play(0); document.body.classList.remove('no-scroll'); } };
CSS
.content{ height:500px; } .column { float: left; width: 50%; } .row:after { content: ""; display: table; clear: both; } .menu-button { position: fixed; background-color: #f2f2f2; outline: none; border: 2px solid black; border-radius: 50%; padding: 0; top: 8px; right: 20px; width: 30px; height: 30px; z-index: 0; cursor: pointer; color: black; } .menu-button:hover{ background-color: #F2FF00 !important; } .menu-button:focus { outline: none; background-color: #f2f2f2; } nav { height: 100vh; display: flex; flex-flow: column wrap; justify-content: center; align-content: center; align-items: center; position: fixed; top: 0; bottom: 0; left: 0; right: 0; background-color: #ff635e; transform: translate3d(-100%, 0, 0); } nav ol { display: flex; flex-flow: column wrap; justify-content: center; align-content: center; align-items: center; position: fixed; } .skew { clip-path: polygon(0 0, 100% 0, 90% 100%, 0 100%); } .vertical { clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%); } .skewback { clip-path: polygon(0 0, -100% 0, 100% 100%, 0 100%); } /* 新增禁止滚动样式 */ .no-scroll { overflow: hidden; }
HTML
<script src="https://unpkg.co/gsap@3/dist/gsap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav id="nav-main" class="skew"> <ol> <li class="link">HOME</li> </ol> </nav> <button id="menu-button" class="menu-button" ><span style="color:black">+</span></button> <div class="content"></div>
关键修改说明
- 添加禁止滚动的CSS类:新增
.no-scroll类,设置overflow: hidden,给body添加该类后,页面将无法滚动。 - 同步滚动控制逻辑:在菜单按钮的点击事件中,根据
toggle的状态(false表示菜单打开,true表示菜单关闭),给body添加或移除.no-scroll类,确保动画和滚动禁用/启用同步执行。
内容的提问来源于stack exchange,提问作者gjjr
相关产品推荐
相关产品推荐

