第一个手风琴默认打开 JavaScript 或 CSS

First accordion to be made open by default either by JavaScript or CSS

我在 Shopify 产品页面中有 3 个手风琴,我打算在页面加载时默认展开第一个。页面加载后,单击其他手风琴应该关闭所有以前打开的手风琴。我只想使用纯 JavaScript(没有像 jQuery 这样的库)或 CSS。我下面的代码只是确保第一个手风琴显示为展开的。在查看页面 https://wv3yau73hiyf9fhv-458195004.shopifypreview.com?

中的手风琴后,您能否帮助更正我的代码
 window.onload = function() {
  var accItem = document.getElementsByClassName('accordion__item');
  // Keep the first accordion open by default.
  for (i = 0; i < accItem.length; i++) {
    console.log("Within first for loop");
    accItem[0].click();
    accItem[i].addEventListener('click', toggleItem, false);
  }
  function toggleItem() {
    var itemClass = this.parentNode.className;
    for (i = 0; i < accItem.length; i++) {
      console.log("Within second for loop");
      accItem[i].className = 'accordion__item close';
    }
    if (itemClass == 'accordion__item close') {
        this.parentNode.className = 'accordion__item open';
    }
  }    
 };

在页面上使用浏览器的控制台,我使用以下命令打开第一个手风琴:

let allAccordions = document.querySelectorAll(".accordion__item");
allAccordions[0].click();

是的,循环也是可能的:

for (var i = 0; i < allAccordions.length; i++) {
    if (i == 0) {
          allAccordions[i].click();
          break; // only the first, can stop looping.
    }
}

最终解决方案如下:

  // Keep the first accordion open by default.
  let allAccordions = document.querySelectorAll(".accordion__item");
  if (allAccordions.length > 0) {
    allAccordions[0].querySelector("input[type=radio]").checked = true;
  }
  // Capture click event for the accordions
  allAccordions.forEach(element => {
    element.addEventListener('click', function() {
      let radioBtn = this.querySelector("input[type=radio]");
      let clickedRadioName = radioBtn.getAttribute("name");

      allAccordions.forEach(element => {
        let elementRadioBtn = element.querySelector("input[type=radio]");
        let elementRadioName = elementRadioBtn.getAttribute("name");
        if ((elementRadioName != clickedRadioName) && elementRadioBtn.checked) {
          element.querySelector("input[type=radio]").checked = false;
        }
      });
    });
  });