使用 transition 过渡属性和 transform 变形属性,让汉堡图标和关闭图标之间进行过渡、变形,形成视觉效果。
适用于h5页面或者app页面中,隐藏菜单和打开菜单时使用。
核心代码部分,简要说明了写法思路;完整代码在最后,可直接复制到本地运行。
1 2 3 4 5 6 |
<label class="label16"> <input class="inp16" type="checkbox"> <span class="line16"></span> <span class="line16"></span> <span class="line16"></span> </label> |
label 标签包裹 input 标签,input 设置为多选按钮,三个 span 标签形成汉堡图标。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
.label16{ width: 48px; height: 36px; display: block; position: relative; cursor: pointer; } .inp16{ display: none; } .line16{ width: inherit; height: 4px; border-radius: 2px; display: block; background-color: #3d3d3d; position: absolute; top: 0; transition: all 0.24s ease-in-out; } .line16:nth-of-type(2){ top: 16px; } .line16:nth-of-type(3){ top: 32px; } .inp16:checked ~ .line16:nth-of-type(1){ transform: rotate(45deg); top: 16px; } .inp16:checked ~ .line16:nth-of-type(2){ width: 0; } .inp16:checked ~ .line16:nth-of-type(3){ transform: rotate(-45deg); top: 16px; } |
隐藏 input 多选按钮,设置 transition 过渡效果,当 input 多选按钮选中时,三个 span 标签设置变形效果,汉堡图标变形过渡到关闭图标。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="style.css"> <title>汉堡菜单按钮</title> </head> <body> <div class="app"> <label class="label16"> <input class="inp16" type="checkbox"> <span class="line16"></span> <span class="line16"></span> <span class="line16"></span> </label> </div> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
/** style.css **/ .app{ width: 100%; height: 100vh; background-color: #ffffff; position: relative; display: flex; justify-content: center; align-items: center; } .label16{ width: 48px; height: 36px; display: block; position: relative; cursor: pointer; } .inp16{ display: none; } .line16{ width: inherit; height: 4px; border-radius: 2px; display: block; background-color: #3d3d3d; position: absolute; top: 0; transition: all 0.24s ease-in-out; } .line16:nth-of-type(2){ top: 16px; } .line16:nth-of-type(3){ top: 32px; } .inp16:checked ~ .line16:nth-of-type(1){ transform: rotate(45deg); top: 16px; } .inp16:checked ~ .line16:nth-of-type(2){ width: 0; } .inp16:checked ~ .line16:nth-of-type(3){ transform: rotate(-45deg); top: 16px; } |