纯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:
- Loop through all accordions and close their panels (removing the
openclass and resetting max-height) - 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
openclass and set its panel’smaxHeighttonull(which closes it, thanks to your CSS transition). - Toggling the Clicked Panel: After closing all other panels, we toggle the
openclass 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

