<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>全选反选案例</title>
<style type="text/css">
.wrap{
width: 60%;
margin: 0 auto;
overflow: hidden;
}
.wrap table{
margin: 140px auto 40px;
width: 100%;
}
.wrap table th{
color: #fff;
background-color: #FF4500;
}
.wrap table tr:hover{
background-color: #eee;
}
.wrap table tr{
height: 40px;
text-align: center;
background-color: #e9e9e9;
}
.wrap table,.wrap table th,.wrap table td{
border: 0;
}
#btn{
width: 20%;
height: 40px;
float: right;
display: block;
background-color: #FF4500;
color: #fff;
border: none;
border-radius: 6px;
}
</style>
</head>
<body>
<div class="wrap">
<table class="gallery">
<tr>
<th><input type="checkbox" id="fuBtn" /></th>
<th>商品</th>
<th>价格(元)</th>
</tr>
<tr>
<td><input type="checkbox" class="zBtn" /></td>
<td>桌子</td>
<td>488</td>
</tr>
<tr>
<td><input type="checkbox" class="zBtn" /></td>
<td>椅子</td>
<td>126</td>
</tr>
<tr>
<td><input type="checkbox" class="zBtn"/></td>
<td>书架</td>
<td>183</td>
</tr>
<tr>
<td><input type="checkbox" class="zBtn" /></td>
<td>衣柜</td>
<td>2300</td>
</tr>
<tr>
<td><input type="checkbox" class="zBtn"/></td>
<td>窗帘</td>
<td>246</td>
</tr>
</table>
<input type="button" id="btn" value="反选" />
</div>
<script type="text/javascript">
var fuBtn = document.getElementById('fuBtn');
var zBtns = document.getElementsByClassName('zBtn');
//全选、全不选
fuBtn.onclick = function(){
for(var i = 0;i < zBtns.length;i++){
zBtn = zBtns[i];
zBtn.checked = this.checked ;
}
}
//如果在全选后,手动取消了一个,此时全选按钮也应该取消被选中;如果手动把每一个选项都选中了,则全选按钮应该自动处于选中状态
//此处的循环是用来循环所有的子checkbox
for(var i = 0;i < zBtns.length;i++){
zBtn = zBtns[i];
//判断是否是checkbox
if(zBtn.type !== 'checkbox'){
//结束当前循环,继续下一次循环
continue;
}
zBtn.onclick = function(){
checkfuBtn();
}
}
//将判断是否子checkbox全部选中与父checkbox的状态封装成函数
function checkfuBtn(){
var isAllChecked = true;
for(var i = 0; i < zBtns.length;i++){
zBtn = zBtns[i];
if(zBtn.type !== 'checkbox'){
continue;
}
if(!zBtn.checked){
isAllChecked = false;
}
}
fuBtn.checked = isAllChecked;
}
//反选
var btn = document.getElementById('btn');
btn.onclick = function(){
for(var i = 0;i < zBtns.length;i++){
zBtn = zBtns[i];
//
//判断是否是checkbox
if(zBtn.type !== 'checkbox'){
//结束当前循环,继续下一次循环
continue;
}
zBtn.checked = !zBtn.checked;
checkfuBtn();
}
}
</script>
</body>
</html>
webAPI03-12全选反选案例
最新推荐文章于 2022-04-13 23:57:19 发布