如何在这款手风琴中一次打开一个标签?

时间:2018-03-16 19:42:13

标签: accordion

原创手风琴来自W3schools网站。 https://www.w3schools.com/howto/howto_js_accordion.asp

我想弄清楚如何只打开一个标签?任何帮助将不胜感激。感谢。

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

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
     } else {
       panel.style.maxHeight = panel.scrollHeight + "px";
     } 
   });
 }

1 个答案:

答案 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");
    for(var it of elems) {
      it.classList.remove("active");
      it.nextElementSibling.style.maxHeight = null;
    }

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

}