简体   繁体   English

Javascript 手风琴标签关闭

[英]Javascript accordion tabs close

I use an accordion that I want to continue to build.我使用了我想继续制作的手风琴。 I would like to close all open tabs if I select another tab so that only one tab is open.如果我选择另一个选项卡以便只打开一个选项卡,我想关闭所有打开的选项卡。 I am very new to Javascript and am trying to get it right.我对 Javascript 很陌生,正在努力把它做好。

Here is my js code:这是我的js代码:

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";
    }
  });
}

the tabs open on click and close again .. I want to close the open tabs when another tab is open .. only one tab should remain open thants what i want thanks :) – Mr.Murphy标签在单击时打开并再次关闭.. 我想在另一个标签打开时关闭打开的标签.. 只有一个标签应该保持打开状态而不是我想要的,谢谢:) – Mr.Murphy

Okay... although I don't know for sure it's that but it looks like:好的...虽然我不确定是这样,但它看起来像:

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";
    }

}); });

You are adding the onclick to your accordion but then you are using this which should close your currently clicked element.要添加onclick到你的手风琴,但是,你正在使用this应该关闭当前点击的元素。 Instead you should create an array and append all opened tabs to it, then close them when a new one opens.相反,您应该创建一个数组并将所有打开的选项卡附加到它,然后在打开一个新选项卡时关闭它们。

Hope it helps, Elias =)希望它有所帮助,埃利亚斯 =)

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

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