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

单页网站移动端导航点击锚点链接后无法折叠的问题求助

解决移动端导航点击锚点后自动折叠的问题

你想的完全没错!咱们确实需要加一段专门的JS代码,来处理菜单里锚点链接的点击事件,让移动端导航在点击后自动折叠起来。

修改后的完整JS代码

把你原有的JS代码替换成下面这段:

$(document).ready(function () { 
    // 汉堡按钮点击事件:切换导航展开/收起状态
    $('.mobile-nav-button').on('click', function() { 
        $( ".mobile-nav-button .mobile-nav-button__line:nth-of-type(1)" ).toggleClass( "mobile-nav-button__line--1"); 
        $( ".mobile-nav-button .mobile-nav-button__line:nth-of-type(2)" ).toggleClass( "mobile-nav-button__line--2"); 
        $( ".mobile-nav-button .mobile-nav-button__line:nth-of-type(3)" ).toggleClass( "mobile-nav-button__line--3"); 
        $('.mobile-menu').toggleClass('mobile-menu--open'); 
        return false; 
    }); 

    // 锚点链接点击事件:自动关闭导航并还原按钮样式
    $('.mobile-menu ul li a').on('click', function() {
        // 收起导航菜单
        $('.mobile-menu').removeClass('mobile-menu--open');
        // 把汉堡按钮从叉号还原成初始的三条横线
        $( ".mobile-nav-button .mobile-nav-button__line:nth-of-type(1)" ).removeClass( "mobile-nav-button__line--1"); 
        $( ".mobile-nav-button .mobile-nav-button__line:nth-of-type(2)" ).removeClass( "mobile-nav-button__line--2"); 
        $( ".mobile-nav-button .mobile-nav-button__line:nth-of-type(3)" ).removeClass( "mobile-nav-button__line--3"); 
    });
});

代码逻辑说明

  • 新增的监听事件专门针对移动端菜单里的所有锚点链接,点击时会执行两个关键操作:
    1. 移除mobile-menu--open类,让导航滑回屏幕右侧,不再遮挡内容
    2. 移除汉堡按钮上的三个变形类,把按钮从关闭状态的叉号还原成初始的汉堡样式
  • 这样用户点击锚点跳转后,导航会自动收起,不需要手动点击关闭按钮,体验更流畅

内容的提问来源于stack exchange,提问作者Mason Viera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:53:28