CSS开关制作
CSS开关制作方法
使用纯CSS可以创建自定义开关效果,无需JavaScript。以下是几种常见的实现方式:
基础复选框开关
通过隐藏原生复选框,使用label和伪元素创建视觉开关:
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(26px);
}
平滑过渡效果
为开关添加动画过渡效果:
.slider {
transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
不同风格变体
创建圆形或方形不同风格的开关:
/* 方形开关 */
.square-slider {
border-radius: 4px;
}
.square-slider:before {
border-radius: 4px;
}
禁用状态
添加禁用状态的样式:
input:disabled + .slider {
opacity: 0.5;
cursor: not-allowed;
}
高级开关实现
使用CSS变量实现可定制颜色的开关:

:root {
--switch-on: #4CAF50;
--switch-off: #ccc;
}
.slider {
background-color: var(--switch-off);
}
input:checked + .slider {
background-color: var(--switch-on);
}
这些方法提供了灵活的方式来创建各种CSS开关效果,可以根据具体需求调整尺寸、颜色和动画效果。





