css制作开关
使用纯CSS制作开关
通过CSS的checkbox hack技术可以实现纯CSS开关效果。核心思路是利用<label>和<input type="checkbox">的联动特性。
<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);
}
添加动画效果的开关
为开关添加更流畅的过渡效果,可以调整transition属性:
.slider {
transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
不同风格的开关设计
-
方形开关:
.slider { border-radius: 0; } .slider:before { border-radius: 0; } -
iOS风格开关:
.slider { background-color: #e9e9eb; } input:checked + .slider { background-color: #34c759; } -
Material Design风格:
.slider { box-shadow: 0 2px 5px rgba(0,0,0,0.2); }
禁用状态样式
为开关添加禁用状态样式:
input:disabled + .slider {
opacity: 0.5;
cursor: not-allowed;
}
响应式尺寸调整
通过CSS变量实现尺寸可配置:
:root {
--switch-width: 60px;
--switch-height: 34px;
}
.switch {
width: var(--switch-width);
height: var(--switch-height);
}
.slider:before {
height: calc(var(--switch-height) - 8px);
width: calc(var(--switch-height) - 8px);
}
input:checked + .slider:before {
transform: translateX(calc(var(--switch-width) - var(--switch-height)));
}






