前言
记得以前写这种类似开关控制都是,由点击事件驱动样式(监听点击事件->动态添加样式)。现在看来总感觉很麻烦。不能确定唯一性,单一值驱动相关事件发生。
自上次总结了自定义 input>radio 单选 checkbox当然也可以自定义,而且就是一个开关。这样就简单多了,根本无需监听点击事件就可以以 input>checkbox 的bool值驱动所有。并且也可以坚定其事件变化。方便~
结构
废话不多说,直接上东西
1 | // 框 + 三个横线 |
样式
结构上已经隐藏了input>checkbox, 所以我们只需添加.icon-menu
.icon-menu_line
样式。
选中状态也可以直接通过input[type=”checkbox”]:checked
判断,无需事件监听动态修改样式,全css判断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// font-size: 16px;
.icon-menu {
position: relative;
box-sizing: border-box;
width: 1.5em;
height: 1.5em;
border: 2px solid #303133;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
cursor: pointer;
.icon-menu_line {
width: 0.75em;
height: 2px;
background: #303133;
display: block;
margin-top: 2px;
transition: all 0.2s ease;
&:nth-of-type(1) {
margin-top: 0;
}
}
input[type="checkbox"]:checked ~ .icon-menu_line {
position: absolute;
margin-top: 0;
&:nth-of-type(1) {
transform: rotate(45deg)
}
&:nth-of-type(2) {
display: none;
}
&:nth-of-type(3) {
transform: rotate(-45deg)
}
}
}
事件监听
使用 checkbox 就很简单了,直接监听 input>checkbox 事件就可以了,没什么麻烦的
Vue Demo
1 | <label class="icon-menu"> |
1 | ... |
React Demo
1 | ... |