实现效果:
代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Switch</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.switch{
margin: 100px 100px ;
position: relative;
display: inline-block;
width: 40px;
height: 20px;
/* background-color: #b12424; */
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.switch .slider {
position: absolute;
cursor: pointer;
background-color: #ff4949;
width: 100%;
height: 100%;
border-radius: 10px;
transition: 0.5s ease;
}
.slider::before{
content: "";
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #ffffff;
transition: 0.5s ease;
}
.slider.active{
background-color: #4CAF50;
}
.slider.active::before{
transform: translateX(20px);
}
</style>
</head>
<body>
<label class="switch ">
<input type="checkbox">
<span class="slider active"></span>
</label>
</body>
<script>
const switchInput = document.querySelector('.switch input[type="checkbox"]');
switchInput.addEventListener('change', function(e) {
// console.log(e.target.checked);
if(!e.target.checked){
document.querySelector('.slider.active').classList.remove('active')
}else{
document.querySelector('.slider').classList.add('active')
}
});
</script>
</html>