我已经开始制作 Accordion 菜单了,html:
<button class="accordion">New Attendees</button>
<div class="panel">
<p>How do I get started?</p>
<p>I'm stuck! Where can I get help?</p>
</div>
<button class="accordion">Instrument Simulations</button>
<div class="panel">
<p>What are some tools I can use?</p>
<p>How can I obtain an estimate?</p>
</div>
使用 CSS:
.accordion:after {
content: "\002B";
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
.accordion:hover {
background-color: #333;
color: white;
}
.active {
background-color: #333;
color: white;
}
.active:after {
content: "\2212";
}
.panel {
padding: 18px;
background-color: white;
display: none;
transition: 0.2s ease-out;
}
我使用 javascript 来赋予它功能:
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
this.classList.toggle("active");
/* Toggle between hiding and showing the active panel */
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
}
}
</script>
现在,所有 Accordion 都在页面加载时折叠,但我希望它们都默认打开。默认情况下打开所有它们的好方法是什么?我想我也许可以将 css 切换到 .panel(display:block;} 但这似乎把其他一切都搞砸了太多而不能那样做。想法?
最佳答案
Javascript 作用于元素本身,因此样式属性应应用于 html,而您将其插入到 css 文件中。这就是为什么一切都搞砸了。
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
this.classList.toggle("active");
/* Toggle between hiding and showing the active panel */
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
}
}
.accordion:after {
content: "\002B";
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
.accordion:hover {
background-color: #333;
color: white;
}
.active {
background-color: #333;
color: white;
}
.active:after {
content: "\2212";
}
.panel {
padding: 18px;
background-color: white;
display: none;
transition: 0.2s ease-out;
}
<button class="accordion active">New Attendees</button>
<div class="panel" style="display:block;">
<p>How do I get started?</p>
<p>I'm stuck! Where can I get help?</p>
</div>
<button class="accordion active">Instrument Simulations</button>
<div class="panel" style="display:block;">
<p>What are some tools I can use?</p>
<p>How can I obtain an estimate?</p>
</div>
关于javascript - Accordion 菜单 : how to open all at start,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48013161/