制作css开关
使用纯CSS创建开关
通过HTML的<input type="checkbox">和CSS的伪元素可以实现纯CSS开关效果。以下是实现代码:
<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);
}
添加动画效果
可以通过调整CSS过渡属性来增强开关的动画效果:

.slider {
transition: all 0.4s cubic-bezier(0.68, -0.55, 0.27, 1.55);
}
.slider:before {
transition: all 0.4s ease-in-out;
}
不同样式的开关
创建圆形开关只需调整边框半径:

.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
禁用状态样式
添加禁用状态的样式可以提升用户体验:
input:disabled + .slider {
opacity: 0.5;
cursor: not-allowed;
}
响应式开关
通过媒体查询调整开关大小以适应不同设备:
@media (max-width: 768px) {
.switch {
width: 50px;
height: 28px;
}
.slider:before {
width: 20px;
height: 20px;
}
input:checked + .slider:before {
transform: translateX(22px);
}
}
这些方法提供了创建CSS开关的基础和进阶技巧,可以根据实际需求进行调整和扩展。