首页 > 技术文章 > CSS+DIV实现开关组件

longhx 2021-03-09 00:05 原文

普通开关按钮

UI效果:将元素设置为背景,再利用元素的::before/::after绘制为开关触点。
交互思路:为元素添加状态样式,更迭背景色以及触点偏移值实现开关转换。当然可以额外添加一个checkbox元素,利用[checked]属性充当状态样式可以省去一些事件监听上的工作

<style>
.na-switch {
    width: 48px;
    height: 24px;
    border-radius: 12px;
    border:0;
    cursor: pointer;
    position: relative;
    padding: 3px;
    font-size: 0;
    background: #B3B3B3;
    transition: all 0.24s ease-out;
    -webkit-transition: all 0.24s ease-out;	
}
.na-switch::before {
    content: '';
    position: absolute;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    top: 4px;
    left: 4px;
    background: #fff;
    transition: all 0.24s ease-out;
    -webkit-transition: all 0.24s ease-out;	
}
.na-switch-on {
    background: #4A90E2;
}
.na-switch-on::before {
    left: 28px; /* 48-6-16 */
}
.na-switch[disabled] {
    cursor: not-allowed;
}
</style>
<h4>开关</h4>
<button class="na-switch"></button>
<button class="na-switch na-switch-on"></button>
<button class="na-switch na-switch-on" disabled></button>

效果如下:

推荐阅读