如何为该手风琴添加自动关闭功能?

时间:2020-10-05 14:47:11

标签: accordion

我创建了我喜欢的手风琴,但是对javascript不太了解,因此不确定如何添加自动关闭功能。我只希望它在选择另一个答案时就关闭答案。

HTML

<button class="accordion">This is a question</button>
<div class="panel">
  <p>This is an answer.</p>
</div>

<button class="accordion">This is another question</button>
<div class="panel">
  <p>This is another answer.</p>
</div>

JS

<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.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  });
}
</script>

非常感谢!

谢谢, 安德烈

0 个答案:

没有答案
相关问题