<!DOCTYPE html>
<html>
<head>
<title>多选框全选,全不选,有一个不选则全选取消</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.slim.min.js"></script>
</head>
<style>
.box,#all{
/*display: none;*/
height:0;
width:0;
}
label{
position: relative;
display: inline-block;
border:1px solid black;
height:20px;
width:20px;
cursor: pointer;
}
label.active{
background: #00FF00;
}
label.active::after{
content: '';
display: block;
position: absolute;
left: 0;
top: 0;
background-image:url("./img/gou.png");//打勾的图片,到阿里巴巴矢量图标库下载即可
background-repeat: no-repeat;
background-size: cover;
background-position: center;
height:20px;
width: 20px;
}
</style>
<body>
全选:<label><input id="all" type="checkbox"/></label> <br/> <br/>
苹果:<label><input type="checkbox" class="box"/></label><br/><br/>
香蕉:<label><input type="checkbox" class="box"/></label><br/><br/>
草莓:<label><input type="checkbox" class="box"/></label><br/><br/>
西瓜:<label><input type="checkbox" class="box"/></label><br/><br/>
</body>
<script>
// window.onload = function (){
console.log($(".box"))
$("#all").on('click',function(){//点击全选框,如果是选中状态则切换成成未选中状态
if($(this).is(":checked")){
$(".box").prop("checked",true);//设置状态
$(".box").parent("label").addClass("active");//添加样式
$("#all").parent("label").addClass("active");
}else{
$(".box").prop("checked",false);
$(".box").parent("label").removeClass("active");
$("#all").parent("label").removeClass("active");
}
// }
});
$(".box").on('click',function(){//子复选框,
console.log(1111)
if ( !$(this).is(":checked") ){//如果有一个没选则父复选框设为不选中的状态
console.log(1111)
$("#all").prop("checked",false);
$(this).parent("label").removeClass("active");
$("#all").parent("label").removeClass("active");
}else{
click();
$(this).parent("label").addClass("active");//如果选了则当前多选框加上选中的样式
}
});
function click(){
// len ++;
var len = 0;//设置初始值
for ( var i = 0; i < $(".box").length; i++){
if ( $(".box").eq(i).is(":checked") ){
len ++;//计算子复选框选中的数量
}
}
console.log(len)
console.log($(".box").length)
if(len==$(".box").length){//选中子复选框的数量和 总的子复选框 的数量相比 相等的话父复选框置成选中状态
$("#all").prop("checked",true);
$("#all").parent("label").addClass("active");
}else{
$("#all").prop("checked",false);
$("#all").parent("label").removeClass("active");
}
}
// }
</script>
</html>
jq多选框全选,全不选,有一个不选则全选取消
猜你喜欢
转载自blog.csdn.net/darkCloudss/article/details/103010158
今日推荐
周排行