如何自动关闭手风琴内部的所有可折叠元素?
我们将在文章中使用 Bootstrap 手风琴组件来演示如何在父手风琴中折叠所有子手风琴。手风琴是一个可折叠组件,有助于在网页上显示展开/折叠类型的內容。
在这篇文章中,我们将使用 Bootstrap 5 手风琴组件以嵌套的方式显示可扩展/可折叠元素列表。现在,首先,我们将通过将事件侦听器附加到父手风琴来侦听“hide”折叠事件。之后,当“hide”折叠事件被触发时,我们将找到该手风琴内的所有可折叠元素,并相应地从这些元素中删除“show”类,以便在 UI 中隐藏它们。
示例
让我们用一个例子来讨论这种方法,如下所示:
附加到手风琴的事件侦听器:
“hide.bs.collapse”
文件名:index.html
<!DOCTYPE html> <html lang="en"> <head> <title>How to automatically close all collapsible elements inside of the accordion when closing the accordion?</title> <link href="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net.cn/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </head> <body> <h3>How to automatically close all collapsible elements inside of the accordion when closing the accordion?</h3> <div class="accordion"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#parent"> Accordion Item #1 </button> <div id="parent" class="accordion-collapse collapse show"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#child-one"> Accordion sub Item #1 </button> <div id="child-one" class="accordion-collapse collapse show"> Accordion sub item 1 - body 1 </div> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#child-two"> Accordion sub Item #1 </button> <div id="child-two" class="accordion-collapse collapse show"> Accordion sub item 1 - body 1 </div> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#child-three"> Accordion sub Item #1 </button> <div id="child-three" class="accordion-collapse collapse show"> Accordion sub item 1 - body 1 </div> </div> </div> <script> const parent = document.getElementById('parent') parent.addEventListener('hide.bs.collapse', function() { const collapsibleEls = this.querySelectorAll('.collapse.show'); collapsibleEls.forEach(el => { el.classList.remove('show') }) }) </script> </body> </html>
结论
在这篇文章中,我们学习了如何在关闭父手风琴时自动关闭手风琴内部的所有可折叠元素,我们通过在父可折叠元素上添加“hide.bs.collapse”事件侦听器实现了这一点。
广告