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

如何设置仅同时显示一个Accordion折叠面板?

Fix: Auto-close Other Accordion Panels When One is Opened

Got it, let's tweak your existing script so that when you click to open one accordion panel, all others automatically close. Your current code works for toggling individual panels, but it doesn't handle resetting the state of the other accordions.

Here's the updated code with comments explaining the changes:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    // First, close all accordion panels and remove active class from all headers
    for (let j = 0; j < acc.length; j++) {
      if (acc[j] !== this) { // Skip the currently clicked one for now
        acc[j].classList.remove("active1");
        let panel = acc[j].nextElementSibling;
        panel.style.maxHeight = null;
      }
    }

    // Now toggle the clicked accordion's state
    this.classList.toggle("active1");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}

What's changed:

  • Added an inner loop that goes through all accordion elements. For each one that isn't the clicked header, we remove the active1 class and set its panel's maxHeight to null (closing it).
  • We only toggle the clicked accordion's state after resetting all others, ensuring only one panel can be open at a time.

This way, whenever you click any accordion header, all other panels will collapse immediately, and the clicked one will either open (if it was closed) or close (if it was already open).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:31:24