created at 2024/12/25 11:46:56
updated at 2024/12/25 11:46:56
HTML
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Switch 开关示例</title>
<style>
/* 定义开关的基本样式 */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* 隐藏实际的 checkbox */
.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: 0.4s;
border-radius: 34px;
}
/* 创建开关的滑动按钮 */
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
border-radius: 50%;
left: 4px;
bottom: 4px;
background-color: white;
transition: 0.4s;
}
/* 当 checkbox 被选中时改变背景色和滑动按钮位置 */
input:checked+.slider {
background-color: #4CAF50;
}
input:checked+.slider:before {
transform: translateX(26px);
}
</style>
</head>
<body>
<h2>CSS 实现的 Switch 开关</h2>
<!-- Switch 开关 -->
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
</body>
</html>