<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>实现复选框的操作</title>
</head>
<body>
<h4>请选择你的爱好:</h4>
<input type="checkbox" id="all">全选/全不选<br>
<input type="checkbox" id="sel2" value="打篮球">打篮球
<input type="checkbox" id="sel2" value="踢足球">踢足球
<input type="checkbox" id="sel2" value="上网">上网
<input type="checkbox" id="sel2" value="写代码">写代码
<input type="checkbox" id="sel2" value="听音乐">听音乐
<br>
<button>全选</button>
<button>全不选</button>
<button>反选</button>
</body>
</html>
<script>
var oall = document.querySelector("#all");
var asel2 = document.querySelectorAll("#sel2");
var abtn = document.querySelectorAll("button")
//全选,全不选
oall.onclick = function () {
if (oall.checked) {
for (var i = 0; i < asel2.length; i++) {
asel2[i].checked = true;
}
} else {
for (var i = 0; i < asel2.length; i++) {
asel2[i].checked = false;
}
}
}
//全选
abtn[0].onclick = function () {
for (var i = 0; i < asel2.length; i++) {
asel2[i].checked = true;
}
}
//全不选
abtn[1].onclick = function () {
for (var i = 0; i < asel2.length; i++) {
asel2[i].checked = false;
}
}
//反选
abtn[2].onclick = function () {
for (var i = 0; i < asel2.length; i++) {
if (asel2[i].checked) {
asel2[i].checked = false;
} else {
asel2[i].checked = true;
}
}
}
</script>