制作css开关
CSS 开关实现方法
纯CSS开关(基于复选框)
利用CSS的:checked伪类和相邻兄弟选择器实现开关效果,无需JavaScript。
<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 {
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
.slider:before {
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
不同风格的开关
方形开关变体:
.slider.square {
border-radius: 0;
}
.slider.square:before {
border-radius: 0;
}
小尺寸开关:
.switch.small {
width: 40px;
height: 22px;
}
.switch.small .slider:before {
width: 16px;
height: 16px;
}
.switch.small input:checked + .slider:before {
transform: translateX(18px);
}
禁用状态处理
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);
}
开关状态文本显示
在滑块上添加ON/OFF文字:
.slider:after {
content: "OFF";
color: white;
display: block;
position: absolute;
transform: translateX(10px);
}
input:checked + .slider:after {
content: "ON";
transform: translateX(-10px);
}






