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

实现手风琴菜单点击新项时自动关闭已展开项

可折叠菜单自动关闭已展开项的解决方案

要实现点击新菜单项时自动关闭之前展开的菜单,只需在原有代码基础上添加关闭其他展开项的逻辑:

修改后的JavaScript代码:

<script>
    var coll = document.getElementsByClassName("collapsible");
    var i;

    for (i = 0; i < coll.length; i++) {
      coll[i].addEventListener("click", function () {
        // 先关闭所有其他展开的菜单
        for (let j = 0; j < coll.length; j++) {
          if (coll[j] !== this) {
            coll[j].classList.remove("active");
            let otherContent = coll[j].nextElementSibling;
            otherContent.style.maxHeight = null;
          }
        }

        // 处理当前点击的菜单
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.maxHeight) {
          content.style.maxHeight = null;
        } else {
          content.style.maxHeight = content.scrollHeight + "px";
        }
      });
    }
</script>

关键逻辑说明:

  • 在处理当前点击项之前,遍历所有可折叠元素,判断是否为当前点击的元素:
    • 如果不是,移除它的active类,并将对应的内容区域maxHeight设为null,强制关闭。
  • 之后再执行原有逻辑,切换当前项的展开/收起状态。

这样就能保证同一时间只有一个菜单处于展开状态,点击新项时自动关闭之前的展开项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:45:34