如何修复我的代码以将 Collapse All div 添加到 Vanilla JS Accordion?

How to Fix my Code to add Collapse All div to Vanilla JS Accordion?

我有使用 HTML 和 CSS 的经验,但我才刚刚开始学习 JS,所以我的代码可能反映了很多。我已经在我的网站中插入了一个 vanilla JS 手风琴,但我也想在页面上添加(最好是多个)Collapse-All 链接。这是我的手风琴 HTML, CSS, 和 JS, 改编自 W3Schools (https://www.w3schools.com/howto/howto_js_accordion.asp):

   <h3 class="accordion">
     ***
   </h3>
   <div class="panel">
     ***
   </div>
   <h3 class="accordion">
     ***
   </h3>
   <div class="panel">
     ***
   </div>
   ...
   div.panel {
     max-height: 0;
     overflow: hidden;
     transition: 0.5s ease-out;
   }
   var accordion = document.getElementsByClassName("accordion");
   var i;

   for (i = 0; i < accordion.length; i++) {
     accordion[i].addEventListener("click", function() {
       var panel = this.nextElementSibling;
       if (panel.style.maxHeight) {
         panel.style.maxHeight = null;
       } else {
         panel.style.maxHeight = panel.scrollHeight + "px";
       }
     });
   }

下面是我自己尝试在accordion JS的基础上添加一个全折叠功能,应该是为了一个click事件遍历我所有的全折叠链接,然后遍历所有的accordion面板找到并关闭所有打开的面板:

   <div class="collapse">
     Collapse All
   </div>
   ...
   <div class="collapse">
     Collapse All
   </div>
   ...
   var collapse = document.getElementsByClassName("collapse");
   var j;

   for (j = 0; j < collapse.length; j++) {
     collapse[j].addEventListener("click", function() {
       var panelAll = document.getElementsByClassName("panel");
       for (k = 0; k < panelAll.length; k++) {
         if (panelAll.style.maxHeight) {
           panelAll.style.maxHeight = null;
         }
       }
     });
   }

但是,在最后一个 for 循环中的“if (panelAll.style.maxHeight)”行,我收到控制台错误,因为 panelAll.style.maxHeight 未定义。这就是我卡住的地方,因为当 panelAll.style.maxHeight 是 null/undefined 时,手风琴的原始 JS 中没有任何控制台错误。是否有任何简单的方法可以解决我的问题,或者我是否需要重新编码整个手风琴 JS 以添加折叠所有功能(在这种情况下我可能会放弃它)?感谢您的任何输入。

您应该尝试 panelAll[k].style.maxHeight,因为 panelAll 是一个数组,而 document.getElementsByClassName returns 是一个集合。

也许这会有所帮助。

[...document.getElementsByClassName("accordion")].forEach(accordion => {
  accordion.addEventListener("click", function() {
    var panel = this.nextElementSibling;
    panel.style.maxHeight = panel.style.maxHeight ? null : panel.scrollHeight + "px";
  });
});

document.getElementById("collapseall").addEventListener("click", () => {
  [...document.getElementsByClassName("accordion")].forEach(accordion => {
    var panel = accordion.nextElementSibling;
    panel.style.maxHeight = null;
  });
});
div.panel {
   max-height: 0;
   overflow: hidden;
   transition: 0.5s ease-out;
}

.accordion {
  cursor: pointer;
}
<button id="collapseall" type="button">
Collapse All
</button>
<h3 class="accordion">
    Accordion-1
  </h3>
  <div class="panel">
    panel-11
  </div>
<h3 class="accordion">
    Accordion-2
  </h3>
  <div class="panel">
    panel-2
  </div>