CSS 如何在关闭手风琴时自动关闭手风琴内的所有可折叠元素
我们将在文章中使用bootstrap的accordion组件来演示如何在父accordion里面折叠所有的子accordion。手风琴是一个可折叠的组件,有助于在网页上显示扩展/折叠类型的内容。
在这篇文章中,我们将使用Bootstrap 5 Accordion组件,以嵌套的方式显示一个可扩展/可折叠元素的列表。现在,首先,我们将通过给父手风琴附加一个事件监听器来监听 “隐藏 “折叠事件。之后,当 “隐藏 “折叠事件被触发时,我们将找到该手风琴内的所有可折叠元素,并因此从这些元素中删除 “显示 “类,以便在用户界面中隐藏它们。
例子
让我们用一个例子来讨论这个方法,下面的例子是
将事件监听器附加到手风琴上 —
"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 “事件监听器来实现。