纯Javascript如何一键隐藏多个元素

时间:2018-09-05 09:19:41

标签: javascript html

我正在构建html手风琴,并且一切正常。但我正在尝试这样做,当您单击以展开手风琴按钮之一时,其内容将展开(显示),而所有其他手风琴内容将被隐藏。

因此,如果我单击手风琴一,则应隐藏手风琴二和三的内容,并且仅显示单击手风琴的内容(手风琴一)。

我想用纯JavaScript做到这一点。我不想使用JQuery $("p").hide(); ,因为我正在做一个纯JavaScript构建感谢:)

我的密码

<button class="accordion">Section 1</button>
<div class="panel" style="display:none;">
  <p>Content one</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel" style="display:none;">
  <p>Content two</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel" style="display:none;">
  <p>Content three</p>
</div>

<script>
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.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    });
}
</script>

2 个答案:

答案 0 :(得分:0)

您可以先隐藏所有其他面板,然后显示当前面板。

var acc = document.getElementsByClassName("accordion");
for (var i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        currentDisplay = panel.style.display === "block" ? "none" : "block";
        var els = document.getElementsByClassName("panel");
        //hide all panels
        [].forEach.call(els, function (el) {
          el.style.display = 'none';
        });
        //display current panel
        panel.style.display = currentDisplay;
    });
}

答案 1 :(得分:0)

您可以这样做

<button class="accordion">Section 1</button>
<div class="panel" style="display:none;">
    <p>Content one</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel" style="display:none;">
    <p>Content two</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel" style="display:none;">
    <p>Content three</p>
</div>



  <script>
        var acc = document.getElementsByClassName("accordion");
        for (var i = 0; i < acc.length; i++) {
            acc[i].addEventListener("click", function () {
                //  this.classList.toggle("active");
                var allPanels = document.getElementsByClassName("panel");
                var panel = this.nextElementSibling;

                for (var i = 0, j = allPanels.length; i < j; i++) {
                    if (allPanels[i].style.display == "block") {
                        allPanels[i].style.display = "none"
                    }
                }
                panel.style.display = "block";

            });
        }
</script>