js实现开关按钮
实现开关按钮的HTML结构
使用<label>和<input type="checkbox">组合实现基础结构,通过CSS隐藏原生复选框:
<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.querySelectorAll('.switch input').forEach(checkbox => {
checkbox.addEventListener('change', function() {
const isChecked = this.checked;
console.log('开关状态:', isChecked);
// 这里可以添加状态变化后的业务逻辑
});
});
添加禁用状态
通过CSS和属性控制禁用样式:
input:disabled + .slider {
opacity: 0.5;
cursor: not-allowed;
}
HTML中设置禁用属性:
<input type="checkbox" disabled>
自定义颜色和尺寸
通过CSS变量实现灵活定制:
.switch {
--switch-width: 60px;
--switch-height: 34px;
--slider-size: calc(var(--switch-height) - 8px);
--active-color: #2196F3;
width: var(--switch-width);
height: var(--switch-height);
}
.slider:before {
width: var(--slider-size);
height: var(--slider-size);
}
input:checked + .slider {
background-color: var(--active-color);
}
动画效果增强
添加弹性动画效果:
.slider:before {
transition: transform 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
无障碍支持
添加ARIA属性和焦点样式:
<input type="checkbox" role="switch" aria-checked="false">
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
