gpt4 book ai didi

Javascript Accordion - 折叠除事件之外的所有打开实例

转载 作者:搜寻专家 更新时间:2023-11-01 05:19:17 26 4
gpt4 key购买 nike

我正在使用一个简单的 javascript Accordion 来打开/关闭列表项,如下所示。是否可以确保在打开新列表项时关闭所有打开的列表项(而不是让每个列表项都打开直到手动关闭的当前方式)?

代码在这里:

https://codepen.io/anon/pen/zejJpJ

JS

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}

HTML

<ul class="track-listing">
<li>
<button class="accordion">TITLE</button>
<div class="panel">
<p>Panel content</p>
</div>
</li>
<li>
<button class="accordion">TITLE</button>
<div class="panel">
<p>Panel content</p>
</div>
</li>
<li>
<button class="accordion">TITLE</button>
<div class="panel">
<p>Panel content</p>
</div>
</li>
</ul>

最佳答案

是的,您可以,在打开新 Accordion 之前关闭所有其他 Accordion :

for (var j = 0; j < acc.length; j++) {
var button = acc[j];

if (button === this) continue;

button.classList.remove("active");
var panel = button.nextElementSibling;
panel.style.maxHeight = null;
}

var acc = document.getElementsByClassName("accordion");

for (var i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
// Close all other accordions
for (var j = 0; j < acc.length; j++) {
var button = acc[j];

if (button === this) continue;

button.classList.remove("active");
var panel = button.nextElementSibling;
panel.style.maxHeight = null;
}

this.classList.toggle("active");
var panel = this.nextElementSibling;

if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
.accordion {
background-color: #1e1e1e;
color: #c0b9b4;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 1em;
transition: 0.4s;
margin: 0 0 2px 0;
}

ul.track-listing {
padding: 0;
margin: 0;
list-style-type: none;
}

.active,
.accordion:hover {
background-color: #c0b9b4;
color: #1e1e1e;
}

.accordion:after {
content: 'LYRICS \002B ';
color: #777;
float: right;
margin-left: 5px;
}

.active:after {
content: "\2212";
}

.panel {
padding: 0 18px;
background-color: #1e1e1e;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
color: #c0b9b4;
}
<ul class="track-listing">
<li>
<button class="accordion">TITLE</button>
<div class="panel">
<p>Panel content</p>
</div>
</li>
<li>
<button class="accordion">TITLE</button>
<div class="panel">
<p>Panel content</p>
</div>
</li>
<li>
<button class="accordion">TITLE</button>
<div class="panel">
<p>Panel content</p>
</div>
</li>
</ul>

关于Javascript Accordion - 折叠除事件之外的所有打开实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54640718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com