案例來(lái)源
本例來(lái)自CodingStartup的視頻:使用 HTML+CSS 制作動(dòng)態(tài) Hamburger Menu
學(xué)到知識(shí)
- 通過(guò)checkbox的偽類(lèi)checked断医,來(lái)綁定菜單,實(shí)現(xiàn)點(diǎn)擊checkbox實(shí)現(xiàn)特效奏纪。
- 使用label嵌套菜單div鉴嗤,并使用for屬性綁定checkbox,實(shí)現(xiàn)點(diǎn)擊菜單本身即可實(shí)現(xiàn)特效序调。
- 在使用transition時(shí)醉锅,要設(shè)置元素的初始狀態(tài),例如本例的top屬性发绢,否則會(huì)出現(xiàn)異常的效果硬耍。
- 使用transform-origin設(shè)置元素原點(diǎn)垄琐,表示從哪個(gè)位置進(jìn)行改變。
主要代碼
html
<body>
<header>
<input type="checkbox" id="toggle">
<label for="toggle">
<div class="hamburger-container">
<span></span>
<span></span>
</div>
</label>
<div class="nav-item">
<ul>
<li>Home</li>
<li>iPhone</li>
<li>iPad</li>
<li>Mac</li>
<li>TV</li>
</ul>
</div>
</header>
</body>
css
#toggle {
display: none;
}
.hamburger-container {
display: block;
width: 20px;
height: 20px;
position: relative;
top: 16px;
}
.hamburger-container span {
display: block;
height: 1px;
background-color: #fff;
position: relative;
transition: top .3s ease-in-out .3s, transform .3s ease-in-out;
top: 0;
}
.hamburger-container span:nth-child(2) {
margin-top: 7px;
}
header {
height: 44px;
background-color: #000;
padding: 0 18px;
}
body {
margin: 0;
padding: 0;
}
#toggle:checked + label .hamburger-container span:nth-child(1) {
transform: rotate(45deg);
top: 4px;
transition: transform .3s ease-in-out .3s, top .3s ease-in-out;
}
#toggle:checked + label .hamburger-container span:nth-child(2) {
transform: rotate(-45deg);
top: -4px;
transition: transform .3s ease-in-out .3s, top .3s ease-in-out;
}
.nav-item {
background-color: rgba(0, 0, 0, .82);
width: 100%;
height: 100vh;
position: absolute;
top: 44px;
left: 0;
transform: scaleY(0);
transition: transform .3s ease-in-out, opacity .3s ease-in-out;
transform-origin: 50% 0;
opacity: 0;
}
#toggle:checked ~ .nav-item {
transform: scale(1);
opacity: 1;
}
ul {
margin-top: 1em;
}
ul li {
color: #fff;
}