CSS 如何在关闭手风琴时自动关闭其中所有折叠元素
我们将使用Bootstrap手风琴组件来演示如何在父手风琴中折叠所有子手风琴。手风琴是一种可折叠的组件,可以帮助在网页上显示可展开/折叠的内容。
在本文中,我们将使用Bootstrap 5手风琴组件以嵌套的方式显示一系列可展开/折叠的元素。首先,我们将监听“隐藏”折叠事件,通过将事件监听器附加到父手风琴上。然后,当“隐藏”折叠事件触发时,我们将找到该手风琴内的所有可折叠元素,并从这些元素中移除“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”事件监听器实现了这一目标。