js 实现switchbutton
实现 Switch Button 的方法
使用 HTML 和 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);
}
添加 JavaScript 交互功能
document.querySelectorAll('.switch input').forEach(checkbox => {
checkbox.addEventListener('change', function() {
const isChecked = this.checked;
console.log('Switch state:', isChecked);
// 可以在这里添加切换后的处理逻辑
});
});
自定义样式选项
通过修改 CSS 可以自定义开关的外观:
- 调整
.switch的width和height改变整体大小 - 修改
.slider的background-color改变关闭状态颜色 - 修改
input:checked + .slider的background-color改变开启状态颜色 - 调整
.slider:before的尺寸改变滑块大小
添加动画效果
在 CSS 中已经包含了过渡效果:

transition: .4s;
可以调整这个时间值来改变切换速度,或者使用 transition-timing-function 改变动画曲线。

响应式设计考虑
使用相对单位可以让开关适应不同屏幕尺寸:
.switch {
width: 3.75rem;
height: 2.125rem;
}
.slider:before {
height: 1.625rem;
width: 1.625rem;
}
无障碍访问增强
为开关添加 ARIA 属性和标签:
<label class="switch">
<input type="checkbox" role="switch" aria-labelledby="switch-label">
<span class="slider"></span>
</label>
<span id="switch-label">Dark Mode</span>






