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

纯JavaScript手风琴:实现点击切换时关闭其他面板需求

Fixing Single-Open Accordion with Vanilla JavaScript

Hey there! I see you’ve been grinding on this accordion issue for a week—let’s get this sorted out for you. The core problem with your current code is that each panel acts independently; we need to add logic to automatically close all other panels when one is opened. Plus, there’s a tiny class name mismatch between your JS and CSS we’ll fix first to make the styling work as intended.

Step 1: Align Class Names

Your CSS uses the open class to style active accordion headers, but your JavaScript was toggling an active class. Let’s fix that to keep everything consistent.

Step 2: Add Logic to Close Other Panels

When you click an accordion, we’ll:

  1. Loop through all accordions and close their panels (removing the open class and resetting max-height)
  2. Toggle the state of the clicked accordion (open if closed, close if already open)

Here’s the corrected JavaScript code:

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

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    // Close all other accordion panels first
    var allAccordions = document.getElementsByClassName("accordion");
    for (var j = 0; j < allAccordions.length; j++) {
      if (allAccordions[j] !== this) {
        allAccordions[j].classList.remove("open");
        var panelToClose = allAccordions[j].nextElementSibling;
        panelToClose.style.maxHeight = null;
      }
    }

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

Breakdown of the Code:

  • Closing Other Panels: When you click an accordion, we first iterate over every accordion on the page. For any accordion that isn’t the one you clicked, we remove the open class and set its panel’s maxHeight to null (which closes it, thanks to your CSS transition).
  • Toggling the Clicked Panel: After closing all other panels, we toggle the open class on the clicked accordion and adjust its panel’s height—opening it if it was closed, or closing it if it was already open.

Quick Check for CSS

Your existing CSS already has the perfect transition for smooth open/close effects. Just make sure your .panel class keeps this line:

transition: 0.2s ease-out;

This should give you the single-open accordion behavior you want without relying on jQuery. Let me know if you hit any snags—I’m happy to help tweak things further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:40:16