<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>全选功能</title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
100px;
height: auto;
border: 1px solid pink;
margin: 30px auto;
border-radius: 5px;
text-align: center;
}
hr{
margin: 10px 0;
}
input{
outline: none;
}
</style>
</head>
<body>
<div class="box">
全选: <input type="checkbox"><br>
<hr>
<input type="checkbox">选项一<br>
<input type="checkbox">选项二<br>
<input type="checkbox">选项三<br>
<input type="checkbox">选项四<br>
</div>
<script>
var allBtn=document.querySelector('input');
var items=document.querySelectorAll('input:nth-child(n+2)');
//选择全选所有选中
allBtn.onclick=function () {
var type=allBtn.checked
for (var i = 0; i < items.length; i++) {
items[i].checked=type
}
}
//判断每一个是否都选择
for (var i = 0; i < items.length; i++) {
items[i].onclick=function () {
var flag=true;
for (var j = 0; j < items.length; j++) {
if (items[j].checked===false){
flag=false;
break;
}
}
allBtn.checked=flag
}
}
</script>
</body>
</html>