jquery를 이용하면 slideup, slidedown 함수를 이용해서 쉽게 아코디언 메뉴를 만들 수 있다
그렇지 않을때 max-height를 이용하거나 내부 컨텐츠의 height를 체크하여 아코디언 메뉴를 만들 수 있으나 더욱 간단하게 쓸 수 있는 방법이 있다
//css
.accordion-content {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows .5s;
}
.accordion-content[aria-hidden="false"] {
grid-template-rows: 1fr;
}
.accordion-content > div {
overflow: hidden;
}
// html
<div class="panel">
<div class="panel-box">
<button type="button" id="title" clss="btn" aria-expanded="false" aria-controls="accordion-content">버튼</button>
<div id="panel-content" class="accordion-content" role="region" aria-labelledby="title" aria-hidden="true">
<div
<p>내용</p>
</div>
</div>
</div>
</div>
// js
const panel = document.querySelector(".panel");
panel.addEventListener("click", (e) => {
const activePanel = e.target.closest(".panel-box");
if (!activePanel) return;
if (e.target.matches(".btn")) {
togglePanel(activePanel);
}
});
function togglePanel(toActive) {
const panelButton = toActive.querySelector(".btn");
const panelContent = toActive.querySelector(".accordion-content");
const panelOpened = panelButton.getAttribute("aria-expanded");
if (panelOpened === "true") {
toActive.querySelector(".btn").setAttribute("aria-expanded", false);
toActive.querySelector(".accordion-content").setAttribute("aria-hidden", true);
} else {
toActive.querySelector("button").setAttribute("aria-expanded", true);
toActive.querySelector(".accordion-content").setAttribute("aria-hidden", false);
}
}
grid-template-rows 의 0fr과 1fr 속성을 이용한 transition으로 자연스러운 슬라이딩 애니메이션이 구현된다
반응형
'Web story > Javascript' 카테고리의 다른 글
동적으로 생성된 요소에 이벤트를 주자 (0) | 2023.06.02 |
---|---|
Intersection Observer API (0) | 2023.06.02 |
이미지 사이즈 확인 (0) | 2020.10.12 |
for문의 최적화 (0) | 2016.11.24 |
스크롤 up, down function (0) | 2015.04.20 |