js实现开关按钮
实现开关按钮的HTML结构
使用<label>和<input type="checkbox">组合实现开关按钮的基础结构。通过CSS隐藏原生复选框,用<span>模拟按钮外观:
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
基础CSS样式
为开关按钮添加视觉样式,包括未激活状态、激活状态和滑块动画效果:
.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.querySelector('.switch input').addEventListener('change', function() {
if(this.checked) {
console.log('开关已打开');
// 执行打开状态的操作
} else {
console.log('开关已关闭');
// 执行关闭状态的操作
}
});
自定义样式扩展
通过修改CSS变量实现颜色和尺寸的快速调整:
:root {
--switch-width: 60px;
--switch-height: 34px;
--slider-color: #ccc;
--active-color: #2196F3;
}
.slider {
width: var(--switch-width);
height: var(--switch-height);
background-color: var(--slider-color);
}
input:checked + .slider {
background-color: var(--active-color);
}
动画效果增强
为开关添加弹性动画或渐变效果提升用户体验:

.slider:before {
transition: transform 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
input:checked + .slider {
box-shadow: 0 0 10px rgba(33, 150, 243, 0.5);
}
无障碍支持
添加ARIA属性确保屏幕阅读器能正确识别控件状态:
<label class="switch">
<input type="checkbox" role="switch" aria-checked="false">
<span class="slider"></span>
</label>
通过JavaScript动态更新ARIA状态:
const switchBtn = document.querySelector('.switch input');
switchBtn.addEventListener('change', function() {
this.setAttribute('aria-checked', this.checked);
});






