为折叠面板(Accordion)添加展开/收起全部按钮的技术求助
实现折叠面板的「展开全部/收起全部」按钮
没问题,我帮你搞定这个需求!下面是完整的可运行代码,你直接替换原来的代码就可以用,我会给你讲清楚每部分的作用:
完整代码
HTML部分
首先我们在所有折叠面板的最上方添加「展开全部」和「收起全部」按钮:
<!-- 控制按钮 --> <button class="accordion-control" id="expandAll">展开全部</button> <button class="accordion-control" id="collapseAll">收起全部</button> <!-- 第一个折叠面板 --> <button class="accordion">test1</button> <div class="panel"> <p> <b>Description :</b><br/><br/> test 1.<br/><br/> <b>DB :</b><br/><br/> test, tes, test<br/><br/> <b>Query:</b><br/><br/> test;<br/><br/> <b>Additional Information:</b><br/><br/> test.<br/><br/> </p> </div> <!-- 第二个折叠面板 --> <button class="accordion">test2</button> <div class="panel"> <p> <b>Description :</b><br/><br/> test 2.<br/><br/> <b>DB :</b><br/><br/> test, tes, test<br/><br/> <b>Query:</b><br/><br/> test;<br/><br/> <b>Additional Information:</b><br/><br/> test.<br/><br/> </p> </div>
CSS部分
给控制按钮加样式,让它和你的折叠面板风格统一,同时调整细节:
/* 控制按钮样式 */ .accordion-control { background-color: #ddd; color: #444; cursor: pointer; padding: 8px; width: 100%; text-align: left; border: none; outline: none; transition: 0.4s; margin-bottom: 8px; /* 和下面的折叠面板拉开距离 */ } .accordion-control:hover { background-color: #ccc; } /* 原来的折叠面板样式 */ .accordion { background-color:#eee; color: #444; cursor: pointer; padding: 8px; width: 100%; text-align: left; border: none; outline: none; transition: 0.4s; margin-bottom: 4px; } .active.accordion:hover { background-color: #ccc; } /* 折叠面板内容样式 */ .panel { padding: 0 18px; background-color: white; display: none; overflow: hidden; margin-bottom: 4px; } .accordion:after { content: '\02795'; /* 加号图标 */ font-size: 13px; color: #777; float: right; margin-left: 5px; } .active:after { content: "\2796"; /* 减号图标 */ } .panel ul, li { line-height: 0.5; }
JavaScript部分
添加控制展开/收起全部的逻辑,同时保留原来的单个面板点击功能:
// 获取所有折叠面板和面板内容 const acc = document.getElementsByClassName("accordion"); const panels = document.getElementsByClassName("panel"); // 单个面板的点击逻辑(保留你原来的功能) for (let i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function() { this.classList.toggle("active"); const panel = this.nextElementSibling; panel.style.display = panel.style.display === "block" ? "none" : "block"; }); } // 展开全部按钮逻辑 document.getElementById("expandAll").addEventListener("click", function() { for (let i = 0; i < acc.length; i++) { acc[i].classList.add("active"); panels[i].style.display = "block"; } }); // 收起全部按钮逻辑 document.getElementById("collapseAll").addEventListener("click", function() { for (let i = 0; i < acc.length; i++) { acc[i].classList.remove("active"); panels[i].style.display = "none"; } });
简单说明
- 按钮会显示在所有折叠面板的最上方,和你的折叠面板风格保持一致
- 点击「展开全部」:所有面板都会打开,同时折叠按钮上的加号会变成减号
- 点击「收起全部」:所有面板都会关闭,减号变回加号
- 原来的单个面板点击功能完全保留,互不影响
你只需要把上面的代码复制替换你原来的代码就可以直接用啦,不用额外配置~
内容的提问来源于stack exchange,提问作者Pankaj Morajkar




