CSS3模拟iOS按钮

昨天在阿里巴巴的笔试上看到有个题要用CSS模拟iOS的按钮:

觉得蛮有意思,顺手做了一下,CSS3做的动画,JQuery加的点击切换:

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
#box {
width: 80px;
height: 50px;
border: 1px solid #e0e0e0;
border-radius: 50px;
}
.on {
background: #64bd63;
}
#box>div,.off {
background: #fff;
}
.on>div {
left: 30px;
}
.off>div {
left: 0;
}
#box>div {
position: relative;
top: 1px;
width: 48px;
height: 48px;
border-radius: 48px;
box-shadow: 0 2px 5px gray;
cursor: pointer;
-webkit-transition: left .2s;
-moz-transition: left .2s;
transition: left .2s;
}

HTML:

1
2
<div id="box" class="on"><div></div></div>

JQuery:

1
2
3
4
5
$(function(){
$("#box").click(function(){
$(this).attr("class",$(this).attr("class")=="on"?"off":"on");
})
})