js 实现switchbutton
以下是在 JavaScript 中实现 SwitchButton 的几种方法:
使用纯 HTML/CSS 和 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 控制:
const toggleSwitch = document.getElementById('toggleSwitch');
toggleSwitch.addEventListener('change', function() {
if(this.checked) {
console.log('Switch is ON');
} else {
console.log('Switch is OFF');
}
});
使用第三方库实现
对于更复杂的需求,可以考虑使用现成的 UI 库:
// 使用 Bootstrap Switch
$("[name='my-checkbox']").bootstrapSwitch();
// 使用 Switchery
var elem = document.querySelector('.js-switch');
var switchery = new Switchery(elem, { color: '#41b7f1' });
创建可重用的 SwitchButton 组件
对于现代前端开发,可以创建 React 组件:
function SwitchButton({ isOn, handleToggle }) {
return (
<label className="switch">
<input
type="checkbox"
checked={isOn}
onChange={handleToggle}
/>
<span className="slider round" />
</label>
);
}
Vue 版本实现:

Vue.component('switch-button', {
template: `
<label class="switch">
<input
type="checkbox"
v-model="isActive"
@change="$emit('change', isActive)"
>
<span class="slider round"></span>
</label>
`,
props: ['value'],
computed: {
isActive: {
get() { return this.value },
set(val) { this.$emit('input', val) }
}
}
});
这些方法提供了从简单到复杂的不同实现方案,可以根据项目需求选择合适的实现方式。






