<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
<style type="text/css">
* {padding: 0;margin: 0;list-style: none;}
#wrap {width: 800px;margin: 50px;font-size: 20px;}
#box {margin-bottom: 20px;}
#box>input {width: 200px;font-size: 50px;}
#content ul li {width: 500px;height: 50px;line-height: 50px;}
#content ul li>input {margin-right: 30px;width: 20px;height: 20px;}
#content ul li:nth-child(odd) {background: #ddd;}
#content ul li:hover {background: cyan;}
</style>
</head>
<body>
<div id="wrap">
<div id="box">
<input type="button" id="allBtn" value="全选"/>
<input type="button" id="noBtn" value="反选"/>
<input type="checkbox" id="cBox"/>
</div>
<div id="content">
<ul>
<li><input type="checkbox"/>选项1</li>
<li><input type="checkbox"/>选项2</li>
<li><input type="checkbox"/>选项3</li>
<li><input type="checkbox"/>选项4</li>
<li><input type="checkbox"/>选项5</li>
<li><input type="checkbox"/>选项6</li>
<li><input type="checkbox"/>选项7</li>
<li><input type="checkbox"/>选项8</li>
<li><input type="checkbox"/>选项9</li>
</ul>
</div>
</div>
</body>
</html>
<script type="text/javascript">
function checkBox() {
var allBtn = document.getElementById("allBtn");
var noBtn = document.getElementById("noBtn");
var cBox = document.getElementById("cBox");
var Li = document.getElementsByTagName("li");
var Input = content.getElementsByTagName("input");
//-----------------全选与反选框后 选择框------
var count = 0;
var max = Li.length;
function isCheck() {
if(count === max) {
cBox.checked = true;
} else {
cBox.checked = false;
}
}
//--------------全选按钮-----------------
Html/CSS/JavaScript
allBtn.onclick = function() {
for(var i = 0; i < Li.length; i++) {
Input[i].checked = true;
}
count = max;
isCheck();
}
//---------------反选按钮---------------
noBtn.onclick = function() {
for(var i = 0; i < Li.length; i++) {
if(Input[i].checked === true) {
Input[i].checked = false;
count--;
isCheck();
} else {
Input[i].checked = true;
count++;
isCheck();
}
}
}
//----------------单选框------------------
//li 标签选择
for(var i = 0; i < Li.length; i++) {
(function(index) {
Li[i].onclick = function() {
if(Input[index].checked === true) {
Input[index].checked = false;
count--;
isCheck();
} else {
Input[index].checked = true;
count++;
isCheck();
}
}
})(i)
}
}
checkBox();
</script>