gpt4 book ai didi

javascript - 我想保持以下 Accordion 的过渡效果

转载 作者:行者123 更新时间:2023-11-28 01:15:44 25 4
gpt4 key购买 nike

我想使用按钮创建嵌套的 Accordion ,但每当我尝试实现它时,它只适用于第一次。

我在上面的例子中只有第一个 Asdf Accordion 起作用,其余的不起作用。

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";
}
});
}
.accordion {
background-color: #f7f7f7;
color: #3985ff;
cursor: pointer;
padding: 15px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 18px;
transition: 0.2s;
text-decoration: underline;
}

.active, .accordion:hover {
background-color: #eee;
}
.accordion:after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}

.active:after {
content: "\2212";
}
.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
<button class="accordion">asdf</button>
<div class="panel">
<p>&#160;</p>
asdf
<button class="accordion">asdf</button>
<div class="panel">
<p>&#160;</p>
asdf
</div>
</div>
<button class="accordion">qwer</button>
<div class="panel">
<p>&#160;</p>
asdf
</div>

我在上面的例子中只有第一个 Asdf Accordion 起作用,其余的不起作用。

最佳答案

问题在于您在单击元素后设置元素高度的方式。见下文。

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

for (var i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
panel.style.maxHeight = '100%';
});
}
.accordion {
background-color: #f7f7f7;
color: #3985ff;
cursor: pointer;
padding: 15px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 18px;
transition: 0.2s;
text-decoration: underline;
}

.active, .accordion:hover {
background-color: #eee;
}
.accordion:after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}

.active:after {
content: "\2212";
}
.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
<button class="accordion">asdf</button>
<div class="panel">
<p>&#160;</p>
asdf
<button class="accordion">asdf</button>
<div class="panel">
<p>&#160;</p>
asdf
</div>
</div>
<button class="accordion">qwer</button>
<div class="panel">
<p>&#160;</p>
asdf
</div>

关于javascript - 我想保持以下 Accordion 的过渡效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51851158/

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