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

问题描述

我创建了我喜欢的手风琴,但是对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>

非常感谢!

谢谢, 安德烈

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)