MENU
- 效果图
- html+css
- html+css+JS
效果图
html+css
html
<div class="s"><input type="checkbox" id="si" class="si"><label for="si" class="sl"></label>
</div>
style
* {margin: 0;padding: 0;box-sizing: border-box;
}body {background-color: rgb(255, 68, 68);display: flex;justify-content: center;align-items: center;min-height: 100vh;
}.s {width: 80px;
}.si {display: none;
}.sl {display: block;width: 80px;height: 40px;border: 2px solid #cccccc;border-radius: 20px;padding: 2px;
}.sl::after {display: block;content: '';width: 50%;height: 100%;position: relative;left: 0;background-color: #acacac;border-radius: 50%;transition: all .5s ease-in;
}.si:checked+.sl::after {left: 50%;
}body:has(.si:checked) {background-color: rgb(68, 68, 255);
}
html+css+JS
html
<div class="s"><input type="checkbox" id="si" class="si" onclick="handleSwitch(this)"><label for="si" class="sl"></label>
</div>
style
:root {--bc: rgb(255, 68, 68);
}* {margin: 0;padding: 0;box-sizing: border-box;
}body {background-color: var(--bc);display: flex;justify-content: center;align-items: center;min-height: 100vh;
}.s {width: 80px;
}.si {display: none;
}.sl {display: block;width: 80px;height: 40px;border: 2px solid #cccccc;border-radius: 20px;padding: 2px;
}.sl::after {display: block;content: '';width: 50%;height: 100%;position: relative;left: 0;background-color: #acacac;border-radius: 50%;transition: all .5s ease-in;
}.si:checked+.sl::after {left: 50%;
}
function handleSwitch(event) {let body = document.querySelector('body');if (event.checked) {body.style.setProperty('--bc', 'rgb(68, 68, 255)');} else {body.style.setProperty('--bc', 'rgb(255, 68, 68)');}
}