今天我们来探讨switch开关选择器是如何实现的,演示效果如下:
未启动状态:
启动后状态:
基本思路:
将表单元素checkbox进行重新定义,-webkit-appearance就是为了重新定义而设置的属性
<!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>Document</title><style>* {margin: 0;padding: 0;/* 盒子的大小默认 width 内容的宽度 */-webkit-box-sizing: border-box;box-sizing: border-box; /* 它是把整个盒子的大小分配为width和height */}body {--weui-FG-3: rgba(0, 0, 0, 0.1);--weui-BRAND: #07c160;--weui-BG-3: #f7f7f7;}.weui-switch {-webkit-tap-highlight-color: transparent;/* -webkit-appearance: 让表单元素重头做人 *//* -webkit chrom 浏览器内核,这只在chrom中有用,但在手机端-webkit统一了天下 */-webkit-appearance: none;/* css世界组织 浏览器对form表单元素样子重置的样式 */appearance: none;/* -ms-appearance: none; *//* 微软的 ms,但是没有微软手机,所以不用 */position: relative;width: 52px;height: 32px;/* css4 css variable */border: 2px solid var(--weui-FG-3);/* outline: 1px solid red; 轮廓:不在五行之内 */outline: 0;border-radius: 16px;/* 盒子的大小默认 width 内容的宽度 */-webkit-transition: background-color 0.1s, border 0.1s;transition: background-color 0.1s, border 0.1s;}.weui-switch:checked {background-color: var(--weui-BRAND);border-color: var(--weui-BRAND);}.weui-switch:before {content: '';position: absolute;/* 不要再开发页面结构的时候用定位 */top: 0;left: 0;bottom: 0;right: 0;border-radius: 15px;background-color: var(--weui-BG-3);/* transform是变形属性 */transition: transform 0.35s ease,-webkit-transform 0.35s ease;}.weui-switch:after {content: " ";position: absolute;top: 0;left: 0;width: 28px;height: 28px;border-radius: 15px;background-color: #fff;box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);transition: transform 0.35s ease, -webkit-transform 0.35s ease;}.weui-switch:checked:after {-webkit-transform : translateX(20px);transform: translate(20px);}.weui-switch:checked:before {-webkit-transform: scale(0);transform: scale(0);}</style> </head><body><input type="checkbox" class="weui-switch"></body></html>
小结
这是一个标准的开关组件,更加符合用户的体验,更加的拟物
由苹果发明
良好的兼容性
①No.2 可以取消表单元素的样式:-webkit-appearance
② -webkit-transform
③ -webkit-box-sizing
④No.1 高亮:-webkit-tap-heightlight-color
⑤ -webkit-transition: transform, -webkit-transform
–创意
:before 看过去没有用 , 但是极具表现力 transform : scale(0)
translateX 平移
如果觉得《微信Switch组件-switch按钮》对你有帮助,请点赞、收藏,并留下你的观点哦!