我无法打开手风琴的第一个元素,以便稍后在单击时将其关闭等。
const accordions = document.querySelectorAll(".accordion");
if(accordions) {
const openAccordion = (accordion) => {
const content = accordion.querySelector(".accordion__content");
accordion.classList.add("open");
content.style.maxHeight = content.scrollHeight + "px";
};
const closeAccordion = (accordion) => {
const content = accordion.querySelector(".accordion__content");
accordion.classList.remove("open");
content.style.maxHeight = null;
};
accordions.forEach((accordion) => {
const intro = accordion.querySelector(".accordion__control");
const content = accordion.querySelector(".accordion__content");
intro.onclick = () => {
if (content.style.maxHeight) {
closeAccordion(accordion);
} else {
accordions.forEach((accordion) => closeAccordion(accordion));
openAccordion(accordion);
}
};
});
}
.accordion__content {
max-height: 0;
overflow: hidden;
will-change: max-height;
-webkit-transition: all 0.6s ease-out;
-o-transition: all 0.6s ease-out;
transition: all 0.6s ease-out;
-webkit-box-sizing: content-box;
box-sizing: content-box;
}
<ul class="">
<li class="accordion">
<button class="accordion__control" aria-expanded="false">
кнопка
</button>
<div class="accordion__content" aria-hidden="true">
<div class="">
контент
</div>
</div>
</li>
<li class="accordion">
<button class="accordion__control" aria-expanded="false">
кнопка
</button>
<div class="accordion__content" aria-hidden="true">
<div class="">
контент
</div>
</div>
</li>
</ul>
要使第一个手风琴元素在页面加载时打开并添加单击时关闭它的功能,您需要稍微更改脚本。我们将添加一个函数来打开第一个元素并调整事件处理程序以考虑当前打开的元素。这是更新后的脚本: