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

如何通过JavaScript修复窗口调整时子菜单自动展开的问题?

问题描述

当前代码存在逻辑问题:窗口从桌面端(≥1080px)缩小到移动端(≤1080px)时,未点击汉堡按钮的情况下下拉菜单会自动展开,不符合预期。目前其他功能正常:窗口放大到桌面端时菜单会关闭;若已点击汉堡按钮,窗口缩放时菜单能保持展开状态。希望通过快速修改现有JavaScript代码解决该问题,无需重写。

现有代码:

let widthMatch = window.matchMedia("(min-width: 1080px)");
let widthMatch2 = window.matchMedia("(max-width: 1080px)");
// mm in the function arg is the matchMedia object, passed back into the function
widthMatch.addEventListener('change', function(mm) {
  if (mm.matches) {
    // it matches the media query: that is, min-width is >= 1080px
    if (burgerDivEle.classList.contains('on') && navUlEle.classList.contains('nav-active')) { //bigger than 1080p clean up classes, so the nav bar is in the original state.
      nav.classList.remove("nav-active");
      burger.classList.remove('on');
    } else if (!burgerDivEle.classList.contains('on') && !navUlEle.classList.contains('nav-active'))
      widthMatch2.addEventListener('change', function(mm) { //shrink it back down to 1080p, re-add it, only under the condition that we removed it first.
        if (mm.matches) {
          nav.classList.add("nav-active");
          burger.classList.add('on');
        }
      });
  }

});
快速修复方案

问题根源在于你给widthMatch2绑定的change事件——当桌面端状态下菜单是收起的,这段代码会在窗口缩小到移动端时自动给菜单加上展开类,完全违背了“点击汉堡才展开”的逻辑。直接删掉这部分冗余代码即可。

修改后的代码:

let widthMatch = window.matchMedia("(min-width: 1080px)");

widthMatch.addEventListener('change', function(mm) {
  if (mm.matches) {
    // 窗口切换到桌面端时,强制收起菜单,恢复初始状态
    nav.classList.remove("nav-active");
    burger.classList.remove('on');
  }
});

额外注意:确保移动端初始状态下,菜单是通过CSS默认隐藏的(比如设置display: none),只有点击汉堡按钮时才添加nav-active类来显示菜单。这样窗口缩小到移动端时,菜单会保持默认收起状态,只有用户主动点击汉堡按钮才会展开。

内容的提问来源于stack exchange,提问作者Jason Huang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:25:37