一次显示折叠内容

时间:2018-06-25 20:46:12

标签: javascript jquery css

我发现了一些非常有用的教程,可以帮助我使用JavaScript来扩展和折叠内容,但是现在我不知道如何使其一次只能扩展一个。因此,当一个div扩展时,如果单击以展开另一个,它会折叠第一个。有任何想法吗?这是我遵循的教程

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.maxHeight) {
      content.style.maxHeight = null;
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
    }
  });
}
.collapsible {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.content {
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="collapsible"> Expand </button>
<div class="content">
  <p>Some content</p>
</div>

1 个答案:

答案 0 :(得分:1)

您可以选择所有<div class="content">,然后将每个设置为display: none。下面的代码段:

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

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    
    //add new code here
    var contents = document.querySelectorAll('div.content')
    contents.forEach((content) => {
    	content.style.display = "none"
    })
    
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}
.collapsible {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.content {
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}
<button class="collapsible"> Expand </button>
<div class="content">
  <p>Some content</p>
</div>
<button class="collapsible"> Expand </button>
<div class="content">
  <p>Some content2</p>
</div>

希望这会有所帮助