<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
list-style: none;
}
body {
padding: 20px;
}
li {
float: left;
margin: 20px;
}
#total {
clear: both;
}
</style>
<script type="text/javascript">
window.onload = function () {
// 获取元素
var all = document.getElementById('all');
var list = document.getElementById('list');
var inputs = list.getElementsByTagName('input');
var total = document.getElementById('total');
// 计算已选项的总数
function showTotal(){
var selected = 0 ;
for (var i = 0 ; i<inputs.length;i++){
if(inputs[i].checked){
selected += 1 ;
}
total.innerHTML = '已选:'+ selected+ '项';
}
}
// 全选事件
all.onchange = function () {
for (var i = 0 ; i<inputs.length;i++){
inputs[i].checked = all.checked;
showTotal();
}
};
// 每个选项的事件
for (var i = 0; i<inputs.length; i++) {
inputs[i].onchange = function () {
showTotal();
if (!this.checked) {
all.checked = false;
}
};
}
}
</script>
</head>
<body>
<div><label><input id="all" type="checkbox"/>全选</label></div>
<ul id="list">
<li><label><input type="checkbox"/>选项1</label></li>
<li><label><input type="checkbox"/>选项2</label></li>
<li><label><input type="checkbox"/>选项3</label></li>
<li><label><input type="checkbox"/>选项4</label></li>
<li><label><input type="checkbox"/>选项5</label></li>
<li><label><input type="checkbox"/>选项6</label></li>
</ul>
<div id="total">已选:0 项</div>
</body>
</html>