CSS 交互 - 可切换的开关

本贴最后更新于 1682 天前,其中的信息可能已经东海扬尘

2019-08-21

描述

使用纯 CSS 构建一个可切换的开关。

HTML

<input type="checkbox" id="toggle" class="offscreen" /> <label for="toggle" class="switch"></label>

CSS

.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 20px;
  background-color: rgba(0, 0, 0, 0.25);
  border-radius: 20px;
  transition: all 0.3s;
}
.switch::after {
  content: '';
  position: absolute;
  width: 18px;
  height: 18px;
  border-radius: 18px;
  background-color: white;
  top: 1px;
  left: 1px;
  transition: all 0.3s;
}
input[type='checkbox']:checked + .switch::after {
  transform: translateX(20px);
}
input[type='checkbox']:checked + .switch {
  background-color: #7983ff;
}
.offscreen {
  position: absolute;
  left: -9999px;
}

Demo

说明

这个效果只能把开关的样式使用到 <label> 元素上,让 label 标签看上去像一个开关。然后通过把 <input> 复选框定位到屏幕外,让用户看不到他的存在。当点击 label 的时候就会关联到 <input> 元素,进而可以改变 <input> 复选框上的 :checked 属性。

  1. <label> 中的 for 属性值和 <input> 选中框元素中的 id 属性值相等时,就可以将两者进行关联
    attribute associates the <label> with the appropriate <input> checkbox element by its id.
  2. .switch::after<label> 创建了一个伪元素,用来做为开关的圆形按钮
  3. input[type='checkbox']:checked + .switch::after 当复选框选中时,定义其后 <label> 中伪元素的样式
  4. transform: translateX(20px) 当复选框选中时,把伪元素(圆形按钮)向右移动 20 px
  5. background-color: #7983ff; 当复选框选中时,让开关开启的背景色和未开启的背景色不同
  6. .offscreen 由于真实可见的开关中并不需要 <input> 复选框元素的展现,因此需要把他脱离文档流并定位到远离视图的地方去。但我们不能隐藏他,否则键盘和屏幕阅读器就无法访问到他了
  7. transition: all 0.3s 当任何属性发生变化时,都将使用 0.3 秒对其进行过渡。因此当复选框被选中时,<label>background-color 和伪元素的 transform 属性都会发生过渡效果

浏览器支持

支持率:97.7%
支持情况:https://caniuse.com/#feat=transforms2d
⚠️:所有支持需要前缀

返回总目录

每天 30 秒系列之 CSS

  • 30Seconds

    📙 前端知识精选集,包含 HTML、CSS、JavaScript、React、Node、安全等方面,每天仅需 30 秒。

    • 精选常见面试题,帮助您准备下一次面试
    • 精选常见交互,帮助您拥有简洁酷炫的站点
    • 精选有用的 React 片段,帮助你获取最佳实践
    • 精选常见代码集,帮助您提高打码效率
    • 整理前端界的最新资讯,邀您一同探索新世界
    488 引用 • 383 回帖 • 1 关注
  • CSS

    CSS(Cascading Style Sheet)“层叠样式表”是用于控制网页样式并允许将样式信息与网页内容分离的一种标记性语言。

    180 引用 • 446 回帖 • 4 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • nolanlee 1

    去掉 checkbox 默认样式也可以考虑用 appearance

    #toggle {
      -moz-appearance: none;
      -webkit-appearance: none;
      margin: 0;
      display: inline;
    }
    
Vanessa
我们终此一生,就是要摆脱他人的期待,找到真正的自己。 昆明