CheckBox全选,半选,不选三种样式原生实现

效果图

代码

<!DOCTYPE html>
<html>
<head><title>复选框样式示例</title>
  <style>

    input[type="checkbox"] {
      display: none; /* 隐藏原生复选框 */
    }

    label.checkbox {
      position: relative;
      display: inline-block;
      width: 20px;
      height: 20px;
      margin-right: 10px;
      border: 1px solid #ccc;
      border-radius: 3px;
      cursor: pointer;
    }

    label.checkbox::before {
      content: "";
      position: absolute;
      top: 2px;
      left: 2px;
      width: 16px;
      height: 16px;
      background-color: #fff;
      border-radius: 2px;
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, .1);
      transition: all .2s;
    }

    input[type="checkbox"]:checked + label.checkbox::before {
      background-color: #007bff;
    }

    input[type="checkbox"]:checked + label.checkbox::after {
      content: "\2713";
      position: absolute;
      top: 1px;
      left: 4px;
      font-size: 14px;
      color: #fff;
    }

    input[type="checkbox"]:indeterminate + label.checkbox::before {
      background-color: #ffc107;
    }

    input[type="checkbox"]:indeterminate + label.checkbox::after {
      content: "\2212";
      position: absolute;
      top: 1px;
      left: 5px;
      font-size: 14px;
      color: #fff;
    }
  </style>
</head>
<body>

<input type="checkbox" id="checkAll">
<label class="checkbox" for="checkAll"></label>

<input type="checkbox" id="check1">
<label class="checkbox" for="check1"></label>

<input type="checkbox" id="check2">
<label class="checkbox" for="check2"></label>

<script>
  const checkAll = document.getElementById('checkAll');
  const checkboxes = document.querySelectorAll('input[type=\'checkbox\']');
  checkAll.addEventListener('click', function() {
    for (let i = 0; i < checkboxes.length; i++) {
      checkboxes[i].checked = checkAll.checked;
    }
  });
  checkboxes.forEach(function(checkbox) {
    checkbox.addEventListener('click', function() {
      let checkedCount = document.querySelectorAll('input[type=\'checkbox\']:checked').length;
      if (checkedCount === 0) {
        checkAll.checked = false;
        checkAll.indeterminate = false;
      } else if (checkedCount === checkboxes.length) {
        checkAll.checked = true;
        checkAll.indeterminate = false;
      } else {
        checkAll.checked = false;
        checkAll.indeterminate = true;
      }
    });
  });

</script>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值