js 实现开关
使用 HTML 和 JavaScript 实现开关
创建一个基本的开关按钮需要结合 HTML 结构和 JavaScript 交互逻辑。以下是一个简单实现方式:
HTML 部分
<label class="switch">
<input type="checkbox" id="toggleSwitch">
<span class="slider round"></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;
}
.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 交互
document.getElementById('toggleSwitch').addEventListener('change', function() {
if(this.checked) {
console.log('开关已打开');
// 执行打开状态的操作
} else {
console.log('开关已关闭');
// 执行关闭状态的操作
}
});
使用第三方库实现开关
对于更复杂的开关需求,可以考虑使用现成的 UI 库:
使用 Bootstrap Switch
<link href="https://cdn.jsdelivr.net/npm/bootstrap-switch@3.3.4/dist/css/bootstrap3/bootstrap-switch.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap-switch@3.3.4/dist/js/bootstrap-switch.min.js"></script>
<input type="checkbox" name="my-switch" data-size="large">
<script>
$("[name='my-switch']").bootstrapSwitch();
</script>
自定义 Vue 开关组件
对于 Vue 项目,可以创建可复用的开关组件:
Vue.component('toggle-switch', {
template: `
<label class="switch">
<input type="checkbox" v-model="isChecked" @change="toggle">
<span class="slider round"></span>
</label>
`,
props: ['value'],
data() {
return {
isChecked: this.value
}
},
methods: {
toggle() {
this.$emit('input', this.isChecked);
}
},
watch: {
value(newVal) {
this.isChecked = newVal;
}
}
});
使用方式:
<toggle-switch v-model="switchState"></toggle-switch>
无障碍访问考虑
确保开关对屏幕阅读器友好:
<label class="switch">
<input type="checkbox" role="switch" aria-checked="false" aria-labelledby="switch-label">
<span class="slider"></span>
</label>
<span id="switch-label">夜间模式</span>
以上实现方式可根据具体项目需求选择或调整,基础版本已包含完整的交互功能和视觉反馈。







