html代码 checkbox单选框控制开关。
<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>
使用css变量方便控制switch的大小。input隐藏,使用span标签修改成显示的样式。
/* 开关 */
/* 开关 - 滑块周围的框 */
.switch {
--width:22px;
position: relative;
display: inline-block;
width: calc(var(--width) * 2);
height: var(--width);
}
/* 隐藏默认 HTML 复选框 */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* 滑块 */
.slider {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
cursor: pointer;
background-color: #ccc;
transition: .4s;
}
/* 轨道*/
.slider.round {
border-radius: 34px;
}
/* 圆形滑块 */
.slider.round::before {
border-radius: 50%;
}
.slider::before {
position: absolute;
content: "OFF"; //控制显示文字
height: var(--width);
width: var(--width);
left: 0px;
bottom: 0px;
background-color: white;
-webkit-transition: .4s;
transition:all .4s;
font-size: 10px;
text-align: center;
line-height: var(--width);
color: #ccc;
}
input:checked+.slider {
background-color: #2196F3;
}
input:checked+.slider:before {
transform: translateX(var(--width));
content: "ON"; //控制显示文字
color: #2196F3;
}