效果预览:效果预览
源码下载:关注公众号【RMRF】,回复【css9】可获取源码
一、HTML
<!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">
<title>switch-theme</title>
<link rel="stylesheet" href="./css/index.css">
</head>
<script>
function handleInput() {
const inputDom = document.getElementsByTagName("input")[0]
const containerDom = document.getElementsByClassName("container")[0]
if (inputDom.checked) {
containerDom.setAttribute("class", 'container open')
} else {
containerDom.setAttribute("class", 'container')
}
}
</script>
<body>
<div class="container">
<label class="switch">
<input type="checkbox" onclick="handleInput()">
<span></span>
</label>
</div>
</body>
</html>
二、CSS样式
* {
padding: 0px;
margin: 0px;
}
.container {
background-color: #000;
height: 100vh;
width: 100vw;
display: flex;
align-items: center;
transition: 0.5s;
}
.open {
background-color: #999;
}
.switch {
position: relative;
display: inline-block;
height: 40px;
width: 75px;
margin: 0px auto;
}
.switch input {
opacity: 0;
}
span {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #202020;
transition: 0.5s;
border-radius: 30px;
}
span:before {
position: absolute;
content: "";
height: 30px;
width: 30px;
border-radius: 50%;
left: 10%;
top: 5px;
box-shadow: inset 8px -4px 0px 0px #ffd500;
background: #202020;
transition: 0.5s;
}
input:checked+span {
background-color: #202020;
}
input:checked+span:before {
transform: translateX(100%);
box-shadow: inset 15px -4px 0px 15px #ffd500;
}