css伪元素实现switch开关

思路: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);  
});
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容