如何在关闭手风琴折叠面板时自动关闭其内部所有可折叠元素?
cssweb developmentfront end technology更新于 2025/1/24 5:00:17
在本文中,我们将使用 Bootstrap 手风琴折叠面板组件演示如何折叠父级手风琴折叠面板内的所有子级手风琴折叠面板。手风琴折叠面板是一种可折叠组件,用于在网页上显示展开/折叠类型的内容。
在本文中,我们将使用 Bootstrap 5 手风琴折叠面板组件以嵌套方式显示可展开/折叠元素列表。首先,我们将通过将事件监听器附加到父级手风琴折叠面板来监听"隐藏"折叠事件。之后,当触发"hide"折叠事件时,我们将找到该手风琴面板内所有可折叠元素,并移除这些元素的"show"类,从而将它们隐藏在用户界面中。
示例
下面我们通过一个示例来讨论这种方法 -
要附加到手风琴面板的事件监听器 -
"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/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/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"事件监听器来实现这一点。
相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

