SnippetUI

自定义切换开关

是原创制作选框的自定实用范例,美观且具有视觉效果。

HTMLCSS

这个代码片段用于将标准复选框替换为现代且美观的拨动开关。利用CSS伪元素和 :checked 伪类,在不使用JavaScript的情况下实现了平滑的动画。

代码

<label class="custom-toggle">
  <input type="checkbox" class="custom-toggle-input" aria-label="Toggle Switch" />
  <span class="custom-toggle-slider"></span>
</label>
/* 拨动开关的容器 */
.custom-toggle {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

/* 隐藏默认复选框 */
.custom-toggle-input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* 滑块背景 */
.custom-toggle-slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #e2e8f0;
  transition: background-color 0.4s;
  border-radius: 34px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 滑块旋钮部分 */
.custom-toggle-slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 选中时的背景色 */
.custom-toggle-input:checked + .custom-toggle-slider {
  background-color: #3b82f6;
}

/* 键盘聚焦时的轮廓线 */
.custom-toggle-input:focus-visible + .custom-toggle-slider {
  outline: 2px solid #3b82f6;
  outline-offset: 2px;
}

/* 选中时旋钮的移动 */
.custom-toggle-input:checked + .custom-toggle-slider:before {
  transform: translateX(26px);
}

实现要点

因为原生的 <input type="checkbox"> 在各浏览器中样式不同,且自定义自由度低,所以在这个代码片段中,我们将复选框本身隐藏,并利用相邻的 <span> 元素(滑块)来构建外观。

  1. 隐藏复选框: 通过设置 opacity: 0 和宽高为 0,在保留功能的同时使其在屏幕上不可见。
  2. 滑块的样式: 使用 ::before 伪元素创建了圆形的“旋钮”部分。
  3. 平滑的动画: 通过指定 transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55),实现了旋钮移动时带有轻微回弹(缓动)的舒适动画效果。
  4. 无障碍考量: 为了让键盘操作时也能清楚知道焦点位置,使用了 :focus-visible 来显示轮廓线。

这款拨动开关在设置界面、深色模式切换等需要直观进行开/关操作的场景中非常活跃。