描述:当点击全选是,选中下面全部的复选框,当复选框全部选中时,点击返现则取消选择,当复选框有没有选中的项的时候,全选按钮取消全选。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>全选和反选 </title>
<style>
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #c0c0c0;
width: 300px;
}
th,
td {
border: 1px solid #d0d0d0;
color: #404060;
padding: 10px;
}
th {
background-color: #09c;
font: bold 16px "微软雅黑";
color: #fff;
}
td {
font: 14px "微软雅黑";
}
tbody tr {
background-color: #f0f0f0;
}
tbody tr:hover {
cursor: pointer;
background-color: #fafafa;
}
</style>
</head>
<body>
<div>
<table>
<thead>
<tr>
<th><input type="checkbox" id="theadInp"></th>
<td>标题</td>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td><input type="checkbox"></td>
<td>1</td>
</tr>
<td><input type="checkbox"></td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
<script>
var topInt = document.getElementById("theadInp");
var tbody = document.getElementById("tbody");
var botInpArr = tbody.getElementsByTagName("input");
topInt.onclick = function () {
for(var i = 0;i<botInpArr.length;i++){
botInpArr[i].checked = this.checked;
}
}
for (var i = 0;i<botInpArr.length;i++){
botInpArr[i].onclick = function () {
//开闭原则
var bool = true;
for(var j = 0;j<botInpArr.length;j++){
if(botInpArr[j].checked===false){
bool = false;
}
topInt.checked = bool;
}
}
}
</script>