css制作开关按钮
使用纯CSS制作开关按钮
通过CSS的checkbox hack技术可以实现无需JavaScript的开关按钮。核心思路是利用<input type="checkbox">与<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);
}
添加动画效果
通过CSS过渡属性可以增强交互体验:
.slider {
transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
不同样式变体
方形开关按钮只需修改边框半径:
.slider.rect {
border-radius: 4px;
}
.slider.rect:before {
border-radius: 2px;
}
禁用状态处理
input:disabled + .slider {
opacity: 0.5;
cursor: not-allowed;
}
尺寸调整技巧
使用CSS变量实现灵活尺寸控制:
.switch {
--switch-width: 60px;
--switch-height: 34px;
--slider-size: calc(var(--switch-height) - 8px);
width: var(--switch-width);
height: var(--switch-height);
}
.slider:before {
width: var(--slider-size);
height: var(--slider-size);
}
input:checked + .slider:before {
transform: translateX(calc(var(--switch-width) - var(--slider-size) - 8px));
}
响应式设计考虑
结合媒体查询适应不同设备:
@media (max-width: 768px) {
.switch {
--switch-width: 50px;
--switch-height: 28px;
}
}






