简体   繁体   中英

Open first JavaScript accordion

How to open the first in a JavaScript accordion? It's a basic accordion with + for opening and - for closing. I'm new to this and I'm only finding solutions for jQuery accordions. Also would like to know if jQuery is the way to go when it comes to accordions?

Here's the jsFiddle: https://jsfiddle.net/dmkx8hg0/

Here's the code:

<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>

You can just trigger the click event for the first element in your 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();

Why not just add active classname and style to your panel, it should do the trick if you want the first panel to open. <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM