打开第一个JavaScript手风琴
问题描述:
如何打开JavaScript手风琴的第一个?这是一个基本手风琴,开盘时为+
,关闭时为-
。我是新来的,我只找到jQuery手风琴的解决方案。也想知道jQuery是否可以在手风琴方面走?打开第一个JavaScript手风琴
这里的的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>
答
你可以只触发单击事件在JavaScript中的第一个元素。 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();
答
为什么不主动添加类名和样式到面板上,如果你想第一个面板中打开它应该做的伎俩。 <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>
在使用Jquery时有什么错误.... ?? –
我正在使用的代码是javascript。因此继续。 –