js实现:
<!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>Document</title>
</head>
<body>
<script type="text/javascript">
window.onload = function(){
var quan = document.getElementById("quan");
quan.onclick = function(){
var aihaos = document.getElementsByName("aihao");
for(var i = 0; i<aihaos.length ; i++){
if(quan.checked){
aihaos[i].checked = true;
}else{
aihaos[i].checked = false;
}
}
}
}
</script>
<input type="checkbox" id="quan"/>
<br>
<input type="checkbox" name="aihao" value="smoke"/>抽烟
<br>
<input type="checkbox" name="aihao" value="drink"/>喝酒
<br>
<input type="checkbox" name="aihao" value="firehair"/>烫头
<br>
</body>
</html>
简化版:
<!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>Document</title>
</head>
<body>
<script type="text/javascript">
window.onload = function(){
var quan = document.getElementById("quan");
quan.onclick = function(){
var aihaos = document.getElementsByName("aihao");
for(var i = 0; i<aihaos.length ; i++){
aihaos[i].checked = quan.checked;
}
}
}
</script>
<input type="checkbox" id="quan"/>
<br>
<input type="checkbox" name="aihao" value="smoke"/>抽烟
<br>
<input type="checkbox" name="aihao" value="drink"/>喝酒
<br>
<input type="checkbox" name="aihao" value="firehair"/>烫头
<br>
</body>
</html>
上面两种都有错误,全部选中后,取消下面任意一个,上面的全选还会打钩,下面是最终的完善版本:
<!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>Document</title>
</head>
<body>
<script type="text/javascript">
window.onload = function(){
var quan = document.getElementById("quan");
var aihaos = document.getElementsByName("aihao");
quan.onclick = function(){
for(var i = 0; i<aihaos.length ; i++){
aihaos[i].checked = quan.checked;
}
}
for(var i = 0; i<aihaos.length ; i++){
aihaos[i].onclick = function(){
var count = aihaos.length;
var checkedCount = 0;
for(var i = 0; i<aihaos.length; i++){
if(aihaos[i].checked){
checkedCount++;
}
}
quan.checked = (count ==checkedCount);
}
}
}
</script>
<input type="checkbox" id="quan"/>
<br>
<input type="checkbox" name="aihao" value="smoke"/>抽烟
<br>
<input type="checkbox" name="aihao" value="drink"/>喝酒
<br>
<input type="checkbox" name="aihao" value="firehair"/>烫头
<br>
</body>
</html>