html实现switch开关

本文介绍了如何使用HTML、CSS和jQuery创建一个简单的文本切换开关,当用户点击时,文本会从关变为开,反之亦然,通过JavaScript实现了状态的实时验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
  <style>
    .text-switch {
      display: none;
    }
    .text-switch + label {
      display: inline-block;
      box-sizing: border-box;
      height: 22px;
      min-width: 44px;
      line-height: 20px;
      vertical-align: middle;
      border-radius: 100px;
      border: 1px solid transparent;
      background-color: rgba(0, 0, 0, 0.25);
      cursor: pointer;
      -webkit-transition: all 0.36s;
      transition: all 0.36s;
      position: relative;
    }

    .text-switch:checked + label {
      background-color: #1890ff;
    }

    .text-switch + label::before {
      content: "";
      display: block;
      width: 18px;
      height: 18px;
      position: absolute;
      left: 1px;
      top: 1px;
      border-radius: 18px;
      background-color: #fff;
      cursor: pointer;
      transition: all 0.36s cubic-bezier(0.78, 0.14, 0.15, 0.86);
      -webkit-transition: all 0.36s cubic-bezier(0.78, 0.14, 0.15, 0.86);
      -webkit-box-shadow: 0 2px 4px 0 rgba(0, 35, 11, 0.2);
      box-shadow: 0 2px 4px 0 rgba(0, 35, 11, 0.2);
    }

    .text-switch:checked + label::before {
      left: 23px;
      transition: all 0.36s cubic-bezier(0.78, 0.14, 0.15, 0.86);
      -webkit-transition: all 0.36s cubic-bezier(0.78, 0.14, 0.15, 0.86);
    }

    .text-switch + label::after {
      content: "关";
      position: absolute;
      top: 1px;
      left: 24px;
      font-size: 12px;
      color: #fff;
    }

    .text-switch:checked + label::after {
      content: "开";
      left: 5px;
    }
  </style>

  <body>
    <div>
      <input type="checkbox" id="text-switch" class="text-switch" />
      <label for="text-switch"></label>
    </div>
    <script>
      // 获取当前开关
      $("#text-switch").on("change", function () {
        if ($(this).is(":checked")) {
          switchStatus = $(this).is(":checked");
          alert(switchStatus); // To verify
        } else {
          switchStatus = $(this).is(":checked");
          alert(switchStatus); // To verify
        }
      });
    </script>
  </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值