效果图如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.switch {
position: relative;
display: inline-block;
width: 50px;
height: 28px;
border-radius: 14px;
/* 使用半径来实现椭圆形状 */
overflow: hidden;
/* 隐藏超出边界的内容 */
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 14px;
/* 跟开关按钮相同的半径 */
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
/* 使用50%的半径值来实现圆形 */
}
input[type="checkbox"]:checked+.slider {
background-color: green;
/* 将开启状态下的背景颜色修改为绿色 */
}
input[type="checkbox"]:checked+.slider:before {
transform: translateX(20px);
}
</style>
</head>
<body>
<label class="switch">
<input type="checkbox" id="toggleButton">
<span class="slider"></span>
</label>
<script>
var toggleButton = document.getElementById("toggleButton");
toggleButton.addEventListener("change", function () {
if (this.checked) {
// 执行开启状态的操作
console.log("按钮已打开");
} else {
// 执行关闭状态的操作
console.log("按钮已关闭");
}
});
</script>
</body>
</html>