Skip to content

Latest commit

 

History

History
93 lines (86 loc) · 2.44 KB

custom-switch.md

File metadata and controls

93 lines (86 loc) · 2.44 KB

自定义开关选择器

?> 背景知识::point_right: transition, 伪元素

同自定义复选框或自定义单选框类似,都是利用一个隐藏的input(:checked)元素 + 一个关联的label元素,通过label元素及其伪元素模拟switch选择器,通过input:checked属性来模拟switch状态是否开启。

<script v-pre type="text/x-template" id="custom-radio"> <style> main { width: 100%; padding: 60px 0; display: flex; justify-content: space-around; align-items: center; flex-wrap: wrap; user-select: none; font: 12px / 1 Helvetica, sans-serif; } label { position: relative; width: 40px; height: 20px; background: lightgrey; border-radius: 10px; cursor: pointer; transition: background .3s; } label[disabled] { cursor: not-allowed; opacity: .5; } label::before, label::after { transition: all .3s; position: absolute; } label::before { content: '关'; top: 4px; left: 22px; color: white; } label::after { content: ''; top: 1px; left: 1px; width: 18px; height: 18px; border-radius: 9px; background: white; } input[type="checkbox"]:checked + label { background: #b4a078; } input[type="checkbox"]:checked + label::before { content: '开'; left: 6px; } input[type="checkbox"]:active + label::after { width: 23px; } input[type="checkbox"]:checked + label::after { left: 21px; } input[type="checkbox"]:checked:active + label::after { left: 16px; } </style> <script> </script> </script>

浏览器支持

<iframe width="100%" height="493px" frameborder="0" src="https://caniuse.bitsofco.de/embed/index.html?feat=transforms2d&periods=future_2,future_1,current,past_1,past_2,past_3&accessible-colours=false"> </iframe>