效果如下:
代码:
<!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> li { list-style: none; } </style> </head> <body> <div class="box1"> <input type="checkbox" id="box1">全选1 </div> <ul> <li><input type="checkbox">1</li> <li><input type="checkbox">2</li> <li><input type="checkbox">3</li> </ul> <div class="box2"> <li><input type="checkbox" id="box2">全选2</li> </div> <script> var input1 = document.querySelector('#box1'); var input = document.querySelector('ul').querySelectorAll('input'); var input2 = document.querySelector('#box2'); //控制第一个全选按钮 input1.addEventListener('click', function () { for (var i = 0; i < input.length; i++) { // this.checked 可以得到当前复选框的选中状态 如果是true 反之就是未选中 input[i].checked = this.checked; input2.checked = this.checked; } }) //控制第二个全选按钮 input2.addEventListener('click', function () { for (var i = 0; i < input.length; i++) { input[i].checked = this.checked; input1.checked = this.checked; } }) // for (var i = 0; i < input.length; i++) { input[i].onclick = function () { var flag = true; //每次点击,查看所有的复选框有没有被选中 for (var i = 0; i < input.length; i++) { if (!input[i].checked) { //只要不是全选,那么就都不选 flag = false; break; //只要有一个没有选中,剩下的没必要判断,终止语句 } } input1.checked = flag; input2.checked = flag; } } </script> </body> </html>