除了下面这种方案实现switch,还可以使用 before + after 配合上 opacity 透明度的 0 和 1,来实现按钮的切换。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8"/>
<style>
:root {
--switch-width: 3em;
--switch-height: calc(var(--switch-width) / 2);
--switch-anim-duration: 0.5s;
font-size: 100%;
}
.switch {
display: none;
}
.switch-label {
width: var(--switch-width);
height: var(--switch-height);
border: 1px solid #AAA;
border-radius: calc(var(--switch-width) / 4);
background-color: #EEE;
cursor: pointer;
display: inline-block;
transition: opacity var(--switch-anim-duration) ease;
position: relative;
}
.switch-label::before {
content: '';
display: inline-block;
width: 50%;
height: 100%;
background-color: white;
border-radius: 100%;
box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.08);
transition: all var(--switch-anim-duration) ease;
position: absolute;
}
/*
相临兄弟选择器(单选) p+ul
兄长选择器(多选) p~ul
子代选择器(多选) p>ul
后代选择器(多选) p ul
*/
.switch:checked~label:before {
transform: translateX(calc(var(--switch-width) / 2));
}
#switch:checked~label {
background-color: green;
}
</style>
<script>
function onStateChange() {
console.log(document.getElementById("switch").checked);
}
</script>
</head>
<body>
<input type="checkbox" id="switch" class="switch" />
<label for="switch" class="switch-label" onclick="onStateChange()"></label>
</body>
</html>