如何设置仅同时显示一个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
active1class and set its panel'smaxHeighttonull(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
相关产品推荐
相关产品推荐

