将复选框转换为切换开关 jQuery switchify

  • 源码大小:7.69KB
  • 所需积分:1积分
  • 源码编号:19JP-3632
  • 浏览次数:298次
  • 最后更新:2023年07月04日
  • 所属栏目:表单
我要下载
加入收藏
本站默认解压密码:19jp.com 或 19jp_com

简介

switchify是一个简单、轻量级的jQuery插件,它可以通过一个JS调用将常规的复选框输入转换为iOS风格的切换开关。

参见:

  • JavaScript和纯CSS中的10个最佳切换开关
  • 10个最佳自定义复选框和无线电输入替换

如何使用它:

1.添加对jQuery库和switchify插件文件的引用。

<!-- jQuery -->
<script src="/path/to/cdn/jquery.min.js"></script>

<!-- switchify -->
<link rel="stylesheet" href="/path/to/src/switchify.css">
<script src="/path/to/src/switchify.js"></script>

2.在复选框输入上初始化插件并完成。

<input class="toSwitch" id="option1" type="checkbox" name="option1" checked />
<input class="toSwitch" id="option2" type="checkbox" name="option2" checked />
<input class="toSwitch" id="option3" type="checkbox" name="option3" />
...
$(function(){
  $('input[type=checkbox]').switchify();
});

3.覆盖开关的默认样式。

label.switchify.switchify-label {
  display: inline-block;
}

label.switchify.switchify-label > input.switchified {
  display: none;
}

label.switchify.switchify-label > span.switchify-switch {
  display: block;
  background-color: #cecece;
  height: 1em;
  width: 1.6em;
  position: relative;
  border: 1px solid #cecece;
  border-radius: 1em;
  transition: background-color 0.25s, border-color 0.25s;
}

label.switchify.switchify-label > span.switchify-switch::after {
  content: "";
  background-color: #fff;
  display: block;
  height: 1em;
  width: 1em;
  position: absolute;
  border-radius: 1em;
  left: 0;
  transition: left 0.25s;
}

label.switchify.switchify-label > input.switchified:checked + span.switchify-switch {
  background-color: #4bcc23;
  border-color: #4bcc23;
}

label.switchify.switchify-label > input.switchified:checked + span.switchify-switch::after {
  left: calc(100% - 1em);
}

预览截图