首页 > 解决方案 > 是否可以一次只打开我的一个折叠式?

问题描述

我正在使用一排排可折叠的东西。我想让我的网站看起来更专业,所以我的目标是让它一次只能打开一个可折叠的。这是我目前使用的 JavaScript:

    var coll = document.getElementsByClassName("collapsible");
    var i;

    for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.display === "block") {
          content.style.display = "none";
        } else {
          content.style.display = "block";
        }
    });
    }

这是可折叠的html:

<button type="button" class="collapsible"></button>
<div class="content"></div>

有什么办法可以让我一次只能打开一个可折叠的?

标签: javascripthtml

解决方案


我会这样做以使其关闭其他打开的行。

这是一个测试:https ://jsfiddle.net/up3t4129/

您需要了解的一件事是确保遍历所有其他打开的,然后关闭它们,这样您就可以获得您想要的结果。

我对代码做了一些评论,以便您更容易理解。

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {

    // here we are gonna loop through the elements
    for(item of coll){
      // and remove .active class on the button
      item.classList.remove("active");

      // here we are checking the next element and making it don't display
      item.nextElementSibling.style.display = "none";
    }
      
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}

推荐阅读