Accordion折叠面板点击自身关闭时背景色与图标无法重置求助
解决Accordion面板点击自身关闭时样式不恢复的问题
问题核心是:点击已展开面板关闭时,代码仅重置了面板高度,但未移除当前按钮的active类,导致背景色和图标无法恢复默认状态。
修改后的JavaScript代码
var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function() { var panel = this.nextElementSibling; if (panel.style.maxHeight) { // 关闭当前面板时,同步移除active类 this.classList.remove("active"); panel.style.maxHeight = null; } else { // 展开新面板前,先关闭所有已展开项 let active = document.querySelectorAll(".accordion-div .accordion.active"); for (let j = 0; j < active.length; j++) { active[j].classList.remove("active"); active[j].nextElementSibling.style.maxHeight = null; } // 给当前面板添加active类并设置展开高度 this.classList.add("active"); panel.style.maxHeight = panel.scrollHeight + "px"; } }); }
完整代码示例
HTML
<div class="accordion-div"> <button class="accordion">Category 1</button> <div class="panel">category text description</div> <button class="accordion">Category 2</button> <div class="panel">category text description</div> <button class="accordion">Category 3</button> <div class="panel">category text description</div> </div>
CSS
.accordion { color: #fff; background-color: #00000042; cursor: pointer; padding: 2px 10px 5px 10px; margin-top: 5px; width: 100%; border: 1px solid #00000042; text-align: left; outline: none; transition: 0.4s; height: 20px; } .active, .accordion:hover { background-color: #71717171; border: 1px solid #00000042; } .accordion:after { content: '\002B'; color: white; font-weight: bold; float: right; margin-left: 5px; } .active:after { content: "\2212"; }
修改说明
- 在关闭面板的分支中新增
this.classList.remove("active"),确保关闭时同步移除激活样式,恢复默认背景色和+图标。 - 展开分支将
toggle改为add,因为前面已清空所有激活状态,直接添加更稳妥,避免toggle带来的状态异常。
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

