效果如下:
html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Title</title>
<script src="js/全选和取消全选.js"></script>
<style>
table {
margin: 100px auto;
border:1px solid #333;
text-align: center;
}
td{
border: 1px solid #333;
height: 70px;
width:80px;
}
thead tr {
font-weight: bold;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<td><input type="checkbox">全选</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox">选择</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><input type="checkbox">选择</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><input type="checkbox">选择</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</body>
</html>
js文件
window.onload = function () {
var aInput = document.getElementsByTagName('input');
for(var i=1; i<aInput.length; i++)
{
aInput[i].onclick=function () {
if(!this.checked)
{
aInput[0].checked=false;
}
var selected=0;
for(var i=1;i<aInput.length;i++){
if(aInput[i].checked){
selected+=1;
}
}
if(selected==aInput.length-1){
aInput[0].checked=true;
}
}
aInput[0].onclick=function () {
for(var i=1; i<aInput.length; i++)
aInput[i].checked=aInput[0].checked;
}
}
}