- html
- <input id="customSwitch" type="checkbox" />
- <label for="customSwitch" class="switch"></label>
- CSS
- /* 定义全局变量 */
- :root {
- --base_color: rgba(0, 0, 0, 0.25);
- --act_color: #5dcb61;
- }
- /* 隐藏 input 输入框 */
- #customSwitch {
- position: absolute;
- left: -9999px;
- }
- /* 设置自定义颜色 */
- .switch {
- position: relative;
- display: inline-block;
- width: 40px;
- height: 20px;
- background-color: var(--base_color);
- border-radius: 20px;
- transition: all 0.3s 0s;
- }
- /* 开关圆球 */
- .switch::after {
- content: "";
- position: absolute;
- top: 1px;
- left: 1px;
- width: 18px;
- height: 18px;
- border-radius: 18px;
- background-color: white;
- transition: all 0.3s 0s;
- }
- input[type="checkbox"]:checked + .switch::after {
- transform: translateX(20px);
- }
- input[type="checkbox"]:checked + .switch {
- background-color: var(--act_color);
- }
核心知识点
隐藏真实 input 输入框, 通过 label for 属性与 input 输入框绑定.
label 标签本身作为椭圆形背景, 用伪类作为开关圆球.
input 选中后, 需要单独设置 label 标签本体和伪类的移动
本系列旨在通过最直接的事例最完整的代码, 解决一些开发中常遇到的实际问题.
例子链接:
喜欢的朋友可以点击关注一波~每天都会更新最实用的项目技巧
有兴趣的小伙伴可以关注一下我的公众号, 互相学习, 共同进步.
来源: https://www.cnblogs.com/bgd150809213/p/12181671.html