css 防止页面加载JS时第一个折叠展开

w80xi6nr  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(185)

我有一个简单的 accordion 开发使用纯javascript没有jQuery和纯CSS也,一切工作正常,问题是,第一个 accordion 扩展时,页面加载,我尝试了许多方法使用CSSJS但它不工作,我在JavaScipt不好,我试图删除active类窗口加载和它删除,但它仍然扩大!你能帮忙吗

// ============== toggle accordion =================//
let header = document.querySelectorAll(".accordion-header");


// ============= get all accoridon header =============//
header.forEach(
  (header) => {
    header.addEventListener("click", function(e) {
      let accordion = document.querySelectorAll(".accordion");
      let parentElm = header.parentElement;
      let siblings = this.nextElementSibling;


      // ============= remove accordion body height ==========//
      accordion.forEach((element) => {
        element.children[1].style.maxHeight = null;
      });

      // =========== toggle active class ==============//
      parentElm.classList.toggle("active");
      if (parentElm.classList.contains("active")) {
        // ============== remove active class from all the accordions ===//
        accordion.forEach((element) => {
          element.classList.remove("active");
        });
        // ============== toggle active class where we clicked ========//

        parentElm.classList.toggle("active");
        // ============= set max height ============//
        if (siblings.style.maxHeight) {
          siblings.style.maxHeight = null;
        } else {
          siblings.style.maxHeight = siblings.scrollHeight + "px";
        }
      }
    });
  }
);

window.onload = function() {
  header[0].click();
}
.accordion-container {
  padding: 0 100px;
}

.accordion .accordion-header {
  padding: 15px 20px;
  cursor: pointer;
  position: relative;
}

.accordion .accordion-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 400;
  line-height: 32px;
  text-decoration: underline;
}

.accordion .accordion-body {
  max-height: 0;
  overflow: hidden;
  transition: max-height ease 0.5s;
  padding: 0 20px;
}

.accordion .accordion-body p {
  font-weight: 400;
  padding-bottom: 20px;
  line-height: 1.5;
}
<div class="accordion">
  <div class="accordion-header">
    <h2>Accordion Header</h2>
  </div>
  
  <div class="accordion-body">
    <p>Accordion Body</p>
  </div>
</div>

<div class="accordion">
  <div class="accordion-header">
    <h2>Accordion Header</h2>
  </div>
  
  <div class="accordion-body">
    <p>
      <p>Accordion Body</p>
    </p>
  </div>
</div>
6ioyuze2

6ioyuze21#

下面的代码将触发点击第一个标题。这会导致 accordion 膨胀。只要删除此代码,它应该停止自动扩展。

window.onload = function() {
  header[0].click();
}

相关问题