以下是一个使用纯 JavaScript 实现的简单开关按钮示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.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;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked+.slider {
background-color: #2196F3;
}
input:focus+.slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked+.slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
</style>
</head>
<body>
<label class="switch">
<input type="checkbox" id="mySwitch">
<span class="slider round"></span>
</label>
<script>
const switchElement = document.getElementById('mySwitch');
switchElement.addEventListener('change', function () {
if (this.checked) {
console.log('开关已打开');
// 在这里可以添加开关打开时的逻辑
} else {
console.log('开关已关闭');
// 在这里可以添加开关关闭时的逻辑
}
});
</script>
</body>
</html>
在上述代码中:
input
元素(类型为checkbox
)来表示开关的状态,CSS 用于美化开关的外观,JavaScript 用于监听开关状态的变化。如果在实现过程中遇到问题,比如开关状态无法正常改变:
getElementById
的 ID 不匹配。领取专属 10元无门槛券
手把手带您无忧上云