要实现的效果如图:
代码实现:
<! 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> </ head> < style> div { margin : 100px auto; width : 900px; } </ style> < body> < input type = " checkbox" id = " selectAll" /> 全选< br /> < input type = " checkbox" class = " checkbox" /> 选项1< br /> < input type = " checkbox" class = " checkbox" /> 选项2< br /> < input type = " checkbox" class = " checkbox" /> 选项3</ body> < script> var selectAll = document. getElementById ( "selectAll" ) ; var checkboxes = document. getElementsByClassName ( "checkbox" ) ; for ( var i = 0 ; i < checkboxes. length; i++ ) { checkboxes[ i] . addEventListener ( "change" , function ( ) { var allChecked = true ; for ( var j = 0 ; j < checkboxes. length; j++ ) { if ( ! checkboxes[ j] . checked) { allChecked = false ; break ; } } selectAll. checked = allChecked; } ) ; } selectAll. addEventListener ( "change" , function ( ) { for ( var i = 0 ; i < checkboxes. length; i++ ) { checkboxes[ i] . checked = selectAll. checked; } } ) ; </ script>
</ html>
完成~