JavaScript Accordion Toggle First Element Active

时间:2017-10-12 10:15:32

标签: javascript

Request a quick help. Got this JS for my accordion. This is the complete script now. QN: How do I modify the JS to enable my first panel element get active/expanded on page load but toggle (as it already does) on click?

Thanks in advance.

    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";
        }
      }
    }
   
  .panel {overflow:hidden;max-height:0}
     <button class="accordion">Section 1</button>
    <div class="panel">My Content 1</div>

    <button class="accordion">Section 2</button>
    <div class="panel">My Content 2</div>

Hope the script can run now.

2 个答案:

答案 0 :(得分:1)

您可以在手风琴菜单

之后加载或创建时使用以下代码
var acc = document.getElementsByClassName("accordion");
acc[0].classList.toggle("active");

答案 1 :(得分:1)

我希望这对你有帮助,我只是触发第一个手风琴的点击功能

    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].click();

   
  .panel {overflow:hidden;max-height:0}
     <button class="accordion">Section 1</button>
    <div class="panel">My Content 1</div>

    <button class="accordion">Section 2</button>
    <div class="panel">My Content 2</div>