思路:1.绘制底部区域 2.伪元素绘制白色圆球 3.点击事件添加_active类
效果图:
html
<div class="switch"></div>
css
.switch{
position: relative;
width: 28px;
height: 14px;
margin: 100px;
border-radius: 14px;
background: #c5c5c5;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
cursor: pointer;
}
/* 白色圆球 */
.switch:after{
content: '';
position: absolute;
left: 1px;
top: 1px;
display: block;
width: 12px;
height: 12px;
border-radius: 12px;
background: #fff;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.37);
transition: left 200ms;
}
.switch._active{
background: #39bcf5;
}
.switch._active:after{
left: 15px;/* 计算移动的距离,总宽28px,圆球宽12px,右侧留1px */
}
js
$(function(){
var fClick = function(){
var jqThis = $(this);
jqThis.toggleClass('_active');
};
$('.switch').on('click',fClick);
});