css3实现的switch开关按钮

前言:
前几天面试的时候被问到如何实现一个开关按钮效果,觉得应该纪录下来,以后的工作中或许会用到。
另外想吐槽一下那个面试官,我说当我遇到不会的问题时会去谷歌搜索,她一脸不屑,谷歌也不一定能搜到答案。我笑了笑,答案可能没有,但思路总会有的。
最后,虽然那家公司也没去成,但这些经历总是让人成长。

下面来说说如何利用css3实现switch开关按钮的效果。网上已经有很多人分享过这个效果,我也看了一些,觉得他们写的很好,所以,吸收精华,提升自我。

考虑到这个效果多用于移动端,因此并未做其它兼容。

首先,我们可以利用input复选框来模拟开关式按钮,并且巧妙利用伪元素,利用伪元素(:before或:after)可以让html代码更简洁。

html代码如下

1
<lable><input class="switch" type="checkbox"/>默认未选中</lable>

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
.switch{
width:3.25em;
height: 2em;
border:1px solid #dfdfdf;
background-color: #fdfdfd;
display: inline-block;
border-radius: 1.25em;
box-shadow: #dfdfdf 0 0 0 0 inset;
background-clip: content-box;
-webkit-appearance:none;
-webkit-user-select: none;
outline: none;
position: relative;
}
.switch:before{
content: '';
width: 1.8em;
height: 1.8em;
position: absolute;
top: 0;
left: 0;
border-radius: 1.25em;
background-color: #fff;
box-shadow: 0 1px 3px rgba(0,0,0,0.4);
}
.switch:checked{
border-color:#64bd63 ;
background-color: #64bd63;
box-shadow: #64bd63 0 0 0 1em inset;
}
.switch:checked:before{
left: 1.4em;
}

下面对其进行优化,加一些简单的过渡动画。
css代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.switch.switch-anim{
transition: background-color ease 0.4s;
}
.switch.switch-anim:before{
transition: left 0.3s;
}
.switch.switch-anim:checked{
box-shadow: #dfdfdf 0 0 0 0 inset;
background-color: #64bd63;
transition: border-color 0.4s, background-color ease 0.4s;
}
.switch.switch-anim:checked:before{
transition: left 0.3s;
}

效果预览点击demo

参考:
css3实现的switch开关按钮