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

如何在点击打开汉堡菜单(hamburger menu)后实现关闭功能?

解决汉堡菜单无法关闭的问题

你的代码目前仅实现了菜单打开逻辑,缺少关闭的切换处理,以下是两种实用修复方案:

方案1:通过判断显示状态直接切换

修改JavaScript函数,让它根据菜单当前的显示状态自动切换显示/隐藏:

function myFunction() {
  const mobileMenu = document.getElementById("mob");
  // 初始状态下元素style.display为空(样式写在CSS中),需同时判断空值与none
  if (mobileMenu.style.display === "none" || mobileMenu.style.display === "") {
    mobileMenu.style.display = "inline-flex";
    mobileMenu.style.position = "absolute";
  } else {
    mobileMenu.style.display = "none";
  }
}

方案2:用CSS类切换(更推荐)

将样式逻辑集中到CSS中,JS仅负责切换类,更易维护:

  1. 更新CSS,新增激活类:
.hamburger {
  width: 35px;
  height: 5px;
  background-color: #f7941e;
  margin: 6px 0;
}

.mobile-menu {
  display: none;
  position: absolute; /* 将position移至默认样式 */
}

/* 新增激活类,控制菜单显示 */
.mobile-menu.active {
  display: inline-flex;
}

.hamburger-container {
  cursor: pointer;
}
  1. 修改JavaScript函数,切换激活类:
function myFunction() {
  document.getElementById("mob").classList.toggle("active");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:10:14