<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <form action = "#" method = ""> <input id="all" type="checkbox"/>全选 <hr /> <div> <input type="checkbox" class="box"/>篮球 <br/> <input type="checkbox" class="box"/>排球 <br/> <input type="checkbox" class="box"/>气球 <br/> <input type="checkbox" class="box"/>足球 <br/> </div> </form> </body> </html>
<script> window.onload = function (){ var all = document.getElementById ("all"); //全选checkbox var box = document.getElementsByClassName('box'); //子复选框 //遍历checkbox,把子复选框的checked设置成全选框的状态,实现全选/全不选 all.onclick = function (){ for ( var i = 0; i < box.length; i++){ box[i].checked = this.checked; } }; //遍历checkbox,子复选框有一个未选中时,如果全选框设为false不选状态 for ( var i = 0; i < box.length; i++){ box[i].onclick = function (){ if ( !this.checked ){ all.checked = false; }else{ all.checked = true; } }; } } </script>