<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>全选反选案例</title>
<style>
table {
width: 350px;
height: 150px;
/* border: 1px solid red; */
border-collapse: collapse
}
table thead {
text-align: center;
height: 40px;
background-color: #008cd0;
color: #fff;
font-size: 20px;
font-weight: bold;
}
table thead tr td {
border: 1px solid #999;
}
table tbody {
height: 160px;
background-color: #f5f0f5;
color: #666;
}
table tbody tr {
height: 40px;
}
table tbody tr td {
border: 1px solid #999;
padding-left: 10px;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<td><input type="checkbox" id="inputNode"></td>
<td>商品</td>
<td>价钱</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>iphone8</td>
<td>8000</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>iPad Pro</td>
<td>5000</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>iPad Air</td>
<td>2000</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>Apple Watch</td>
<td>2000</td>
</tr>
</tbody>
</table>
<script>
// 需求:点击全选框时 复选框也被选中 或不选中
// 复选框都选中时 上面全选框自动勾选
window.onload = function () {
// 获取元素集合
var inputNode = document.getElementById('inputNode');
var inputs = document.querySelectorAll('tbody tr td input');
// 绑定点击事件
inputNode.onclick = function () {
for (var i = 0; i < inputs.length; i++) {
// 点击全选框时 复选框也被选中 或不选中
inputs[i].checked = this.checked;
}
}
// 复选框都选中时 上面全选框自动勾选
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = function () {
var flag = true;
for (var i = 0; i < inputs.length; i++) {
//如果没有被选中
if (!inputs[i].checked) {
// 将返回的结果给flag
flag = false;
break;
}
}
inputNode.checked = flag;
}
}
}
</script>
</body>
</html>