๐ช ์์ฝ๋์ธ ๋ฉ๋ด ๋ง๋ค๊ธฐ
์์ฝ
- .gnb-sub-wrap์ css๋ฅผ ์ค๋ค.
max-height : 0; overflow : hidden; ์์ฑ์ผ๋ก ์ปจํ ์ธ ๊ฐ ์๋ณด์ด๋๋ก
transition : ๋ณด์ฌ์ง ๋ ์ ๋๋ฉ์ด์ ํจ๊ณผ
- gnb > li ๋ฅผ ํด๋ฆญํ๋ฉด
max-height ๊ฐ true ? max-height : 0 : max-height : ์ปจํ ์ธ ์ ๋์ด
1. semantic html tag ์์ฑ
<nav>
<ul id="gnb">
<li>๋ฉ๋ด์๊ฐ
<ul class="gnb-sub-wrap">
<li><a href="#">์๋์์น</a></li>
<li><a href="#">์ฌ๋ฃ</a></li>
</ul>
</li>
<li><a href="#">์ฃผ๋ฌธ์ฐ์ต</a></li>
<li>๋ญํน/๊ฒ์ํ
<ul class="gnb-sub-wrap">
<li><a href="#">๋ญํน</a></li>
<li><a href="#">๊ฒ์ํ</a></li>
</ul>
</li>
<li><a href="#">์ด๋ฒคํธ/๋ด์ค</a></li>
</ul>
</nav>
2. CSS ์์ฑ
#gnb > li:hover{
cursor : pointer;
background-color : skyblue;
}
#gnb .gnb-sub-wrap{
max-height : 0;
overflow : hidden;
transition : max-height .3s ease-in-out;
}
1. max-height + overflow
- max-height ์์ฑ์ element์ ์ต๋ ๋์ด๋ฅผ ์ง์ ํ๋ ์์ฑ์ด๋ค.
- .gnb-sub-wrap ์ด ๋ณด์ฌ์ง ๋, ์ ๋๋ฉ์ด์ ์ ์ฃผ๊ณ ์ถ๋ค๋ฉด display ๋ณด๋ค max-height ์์ฑ์ ์ฌ์ฉํด์ผ ํ๋ค.
- overflow : hidden ์์ฑ์ ์ฌ์ฉํ์ฌ height์ ๋๋ ๋ด์ฉ์ ๋ณด์ด์ง ์๋๋ก ํ๋ค.
2. transition : .gnb-sub-wrap์ด ๋ณด์ฌ์ง ๋ max-height์ ๋ณํ์ ์ ๋๋ฉ์ด์ ์ ์ค๋ค.
3. JS ์์ฑ
const $nav = document.querySelectorAll("#gnb > li");
$nav.forEach((list) => {
list.addEventListener("click", function(){
this.classList.toggle("open");
const panel = this.children[0];
if(panel.classList.contains("gnb-sub-wrap")){
panel.style.maxHeight ? panel.style.maxHeight = null : panel.style.maxHeight = panel.scrollHeight + "px";
}
});
});
1. $nav ๋ณ์์ #gnb > li ์๋ฆฌ๋จผํธ๋ค์ ๊ฐ์ ธ์ ๋ด์์ค๋ค.
2. li ๋ค์ ์ด๋ฒคํธ๋ฅผ ๊ฑธ์ด์ค๋ค.
- ํด๋ฆญ ์ classList.toggle("open")
- #gnb > li ์ ์ฒซ ๋ฒ์งธ ์์์ panel์ ๋ด๊ธฐ(a ํ๊ทธ or .gnb-sub-wrap)
- panel์ด gnb-sub-wrap ์ด๋ฉด maxHeight์ ๋ณ๊ฒฝํด์ฃผ๊ธฐ(scrollHeight์ ์์ ์ปจํ ์ธ ์ ๋์ด = ํ์ฌ ๋ณด์ด์ง ์๋ ์ปจํ ์ธ ์ ์ค์ ๋์ด)