js 实现开关
使用HTML和CSS创建开关样式
创建一个基本的开关样式需要HTML和CSS的配合。HTML提供结构,CSS负责视觉效果。
<label class="switch">
<input type="checkbox">
<span class="slider round"></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;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(26px);
}
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
添加JavaScript交互功能
通过JavaScript监听开关状态变化并执行相应操作。
const toggleSwitch = document.querySelector('.switch input[type="checkbox"]');
function switchTheme(e) {
if (e.target.checked) {
console.log('开关开启');
// 开启状态下的操作
} else {
console.log('开关关闭');
// 关闭状态下的操作
}
}
toggleSwitch.addEventListener('change', switchTheme, false);
使用第三方库实现高级开关
对于更复杂的需求,可以考虑使用第三方库如switchery。

安装switchery:
npm install switchery
使用示例:

import Switchery from 'switchery';
const elem = document.querySelector('.js-switch');
const init = new Switchery(elem, {
color: '#41b7f1',
secondaryColor: '#dedede',
size: 'small'
});
响应式开关实现
确保开关在不同设备上都能良好显示,可以添加响应式设计。
@media screen and (max-width: 600px) {
.switch {
width: 50px;
height: 28px;
}
.slider:before {
height: 20px;
width: 20px;
}
input:checked + .slider:before {
transform: translateX(22px);
}
}
无障碍访问优化
为开关添加适当的ARIA属性,提升无障碍访问体验。
<label class="switch">
<input type="checkbox" role="switch" aria-checked="false">
<span class="slider round"></span>
</label>
const switchInput = document.querySelector('.switch input');
switchInput.addEventListener('change', function() {
this.setAttribute('aria-checked', this.checked);
});






