如何在JavaScript手风琴中打开第一个?它是一个基本的手风琴,+
用于打开,-
用于关闭。我是新手,我只是在寻找jQuery手风琴的解决方案。还想知道jQuery是否是手风琴的最佳选择?
这里是jsFiddle:https://jsfiddle.net/dmkx8hg0/
以下是代码:
<head>
<style>
button.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
button.accordion.active, button.accordion:hover {
background-color: #ccc;
}
button.accordion:after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
button.accordion.active:after {
content: "\2212";
}
div.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
</style>
</head>
<body>
<button class="accordion">Section 1</button>
<div class="panel">
<p>content</p>
</div>
<button class="accordion">Section 2</button>
<div class="panel">
<p>content</p>
</div>
<button class="accordion">Section 3</button>
<div class="panel">
<p>content</p>
</div>
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
}
</script>
</body>
答案 0 :(得分:0)
您只需触发javascript中第一个元素的click事件即可。 Here's an updated fiddle
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
}
acc[0].onclick();
答案 1 :(得分:0)
为什么不直接向面板添加活动的类名和样式,如果您想要打开第一个面板,它应该可以解决问题。
<button class="accordion active">Section 1</button>
<div class="panel" style="max-height: 89px;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>