js 实现开关
使用 HTML 和 JavaScript 实现开关
HTML 部分创建一个简单的开关结构,使用 label 和 checkbox 实现交互:
<label class="switch">
<input type="checkbox" id="toggle">
<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.getElementById('toggle').addEventListener('change', function() {
if(this.checked) {
console.log('开关已打开');
// 打开状态执行的操作
} else {
console.log('开关已关闭');
// 关闭状态执行的操作
}
});
使用按钮元素实现开关
替代方案使用按钮元素实现开关效果:
<button id="powerBtn" class="power-button">OFF</button>
const powerBtn = document.getElementById('powerBtn');
let isOn = false;
powerBtn.addEventListener('click', () => {
isOn = !isOn;
powerBtn.textContent = isOn ? 'ON' : 'OFF';
powerBtn.style.backgroundColor = isOn ? '#4CAF50' : '#f44336';
// 根据状态执行不同操作
if(isOn) {
// 开启功能
} else {
// 关闭功能
}
});
使用第三方库实现
快速集成现有开关组件库:

<!-- 引入库 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-switch@3.3.4/dist/css/bootstrap3/bootstrap-switch.min.css">
<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">
$("[name='my-switch']").bootstrapSwitch();






