效果图
image
原理
switch 只有两个状态, 开 / 关, 跟 input 的 checkbox 一致, 所以我们可以借助 checkbox 完成样式的切换;
一个简单的 input
- <input class="switch-component" type="checkbox">
- CSS
- /* 背景层 */
- .switch-component {
- position: relative;
- width: 60px;
- height: 30px;
- background-color: #dadada;
- border-radius: 30px;
- border: none;
- outline: none;
- -webkit-appearance: none;
- transition: all .2s ease;
- }
- /* 按钮 */
- .switch-component::after {
- content: '';
- position: absolute;
- top: 0;
- left: 0;
- width: 50%;
- height: 100%;
- background-color: #fff;
- border-radius: 50%;
- transition: all .2s ease;
- }
- /* 选中状态时, 背景色切换 */
- .switch-component:checked {
- background-color: #86c0fa;
- }
- /* 选中状态时, 按钮的位置移动 */
- .switch-component:checked::after {
- left: 50%;
- }
往期系列
你可能不知道的 CSS 骚操作 - tab 切换
这个系列会放许多你不知道的 CSS 骚操作, 敬请期待!
image
欢迎所有前端爱好者关注我的个人微信公众号, 我会不定期分享最新, 实用性高的前端文章以及技巧!
来源: http://www.jianshu.com/p/73b614dc62e5