简体   繁体   English

Javascript:单击时关闭所有手风琴?

[英]Javascript: close all accordions when one is clicked?

I'm basically trying to close all the accordions close and only keep one of them open which was clicked. 我基本上是在尝试关闭所有手风琴,只打开其中一个被单击的手风琴。

So, in short term, only keep one tab open. 因此,在短期内,只能保持打开一个选项卡。

This is what I have so far: 这是我到目前为止的内容:

https://jsfiddle.net/gymzfg9r/2/ https://jsfiddle.net/gymzfg9r/2/

and this is the javascript: 这是javascript:

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

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");
  }
}

Could someone please advise on this? 有人可以为此提供建议吗?

insert code for close others: 插入代码以关闭其他人:

  this.classList.toggle("active");

  var arr = document.getElementsByClassName("show");
  for (j = 0; j < arr.length; j++) {
      if(this.nextElementSibling != arr[j])
         arr[j].classList.toggle("show");
  }


  this.nextElementSibling.classList.toggle("show");

this do the job , but i am pretty sure this is a terrible way to do it, just cant recall a better one right now 这可以完成工作,但是我很确定这是一种糟糕的方法,只是现在还想不起更好的方法

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

function closeEverything() {
    var openElements = document.getElementsByClassName("active");
  if(openElements.length) {
    for(var i = 0; i < openElements.length; i++) {
        openElements[i].nextElementSibling.classList.toggle("show");
        openElements[i].classList.toggle("active"); 
     }
    }
}

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
            if(this.classList.contains('active')) {
            this.classList.toggle('active');
            this.nextElementSibling.classList.toggle('show');
        } else {
                closeEverything();
            this.classList.toggle("active");
            this.nextElementSibling.classList.toggle("show");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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