如何在第二次点击时关闭手风琴? (仅适用于CSS和JS)

时间:2018-08-06 13:11:34

标签: javascript html css

我有一个简单的手风琴,当单击一个新手风琴时,它会关闭当前面板。就像我想要的那样工作。

但是,我希望能够通过再次单击来关闭当前打开的面板。为此,我需要添加什么代码?

请不要使用jQuery:)

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    var elems = document.getElementsByClassName("accordion");
    for(var it of elems) {
      it.classList.remove("expanded");
      it.nextElementSibling.style.maxHeight = null;
    }

    this.classList.toggle("expanded");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  });

}
.accordion:after {
    content: '\002B';
}

.expanded:after {
    content: "\2212";
}

.panel {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}
<button class="accordion"></button>
<div class="panel">
	Text 1
</div>

<button class="accordion"></button>
<div class="panel">
	Text 2
</div>

<button class="accordion"></button>
<div class="panel">
	Text 3
</div>

<button class="accordion"></button>
<div class="panel">
	Text 4
</div>

2 个答案:

答案 0 :(得分:0)

请尝试:

var acc = document.getElementsByClassName("accordion");
        var i;      
        for (i = 0; i < acc.length; i++) {
        acc[i].addEventListener("click", function() {
        var elems = document.getElementsByClassName("accordion");
        var setClasses = !this.classList.contains('expanded');
        for(var it of elems) {
            console.log(it);
          it.classList.remove("expanded");
          it.nextElementSibling.style.maxHeight = null;
        }       
        if (setClasses) {
            this.classList.toggle("expanded");
            var panel = this.nextElementSibling;
            panel.style.maxHeight = panel.scrollHeight + "px";
        }       
        });

        }

答案 1 :(得分:0)

这是一个非常短的实现,减少代码量将使您更好地监督代码。

var acc = document.getElementsByClassName("accordion");

function toggle (el) {

  let nextElement = el.nextElementSibling;
  
  nextElement.className === 'panel' ? nextElement.className = '' : nextElement.className = 'panel';

}
.accordion:after {
    content: '\002B';
}

.expanded:after {
    content: "\2212";
}

.panel {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}
<button onclick="toggle(this)" class="accordion"></button>
<div class="panel">
	Text 1
</div>

<button onclick="toggle(this)" class="accordion"></button>
<div class="panel">
	Text 2
</div>

<button onclick="toggle(this)" class="accordion"></button>
<div class="panel">
	Text 3
</div>

<button onclick="toggle(this)" class="accordion"></button>
<div class="panel">
	Text 4
</div>