效果图
代码
<!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>