<body>
<ul>
<li class="li" >
<label><input type="checkbox" checked="true" class="check-father" /><span id="">
adadadadsa
</span></label>
<ul class="child">
<li>
<label><input type="checkbox" checked="true" /><span id="">
adadadadsa
</span></label>
</li>
<li>
<label><input type="checkbox" checked="true" /><span id="">
adadadadsa
</span></label>
</li>
</ul>
</li>
<li class="li" >
<label><input type="checkbox" checked="true" class="check-father" /><span id="">
adadadadsa
</span></label>
<ul class="child">
<li>
<label><input type="checkbox" checked="true" /><span id="">
adadadadsa
</span></label>
</li>
<li>
<label><input type="checkbox" checked="true" /><span id="">
adadadadsa
</span></label>
</li>
</ul>
</li>
<li class="li" >
<label><input type="checkbox" checked="true" class="check-father" /><span id="">
adadadadsa
</span></label>
<ul class="child">
<li>
<label><input type="checkbox" checked="true" /><span id="">
adadadadsa
</span></label>
</li>
<li>
<label><input type="checkbox" checked="true" /><span id="">
adadadadsa
</span></label>
</li>
</ul>
</li>
</ul>
</body>
Ok,body里面的代码差不多就这种结构,没什么异议。
<style>
input{
position: relative;
z-index: 2;
}
input[type="checkbox"]::before{
content: " " ;
position: absolute;
top: 0;
left: 0;
width: 16px;
height: 16px;
line-height: 16px;
text-align: center;
font-size: 16px;
background-color: #fff;
border-radius: 2px;
border: 1px solid #d9d9d9;
}
input[type="checkbox"]:checked::before{
content: "\2714" ;
color: #fff;
background-color: #03a9f4;
}
.check-father:checked::before{
content: "\2714" !important;
color: #fff;
background-color: #03a9f4;
}
.check-other:checked::before{
content: "\2501" !important;
color: #fff;
background-color: #03a9f4;
}
ul{
list-style-type: none;
}
.child{
padding-left:20px ;
}
</style>
css代码的话,我们使用的是自定义的伪类元素,为了使的复选框更好看。原生的checkBox着实不好看。
<script>
let fatherList=document.querySelectorAll('.li>label>input');
fatherList.forEach(father=>{
let domList=father.parentNode.parentNode.querySelector("ul").querySelectorAll('input');
father.addEventListener('change',function(e){
console.log(this.checked)
console.log(domList)
let _this=this;
if(this.checked){
this.classList.replace('check-other','check-father')
}
domList.forEach(dom =>{
dom.checked= _this.checked;
})
})
domList.forEach(dom=>{
dom.addEventListener('change',function(){
let allCheck=[].slice.call(domList).every(item => item.checked);
let allUnCheck=!( [].slice.call(domList).some(item => item.checked) );
if(allCheck){
father.checked=true;
father.classList.replace('check-other','check-father')
}else if(allUnCheck){
father.checked=false;
}else{
father.checked=true;
father.classList.replace('check-father','check-other')
}
console.log('allUnCheck',allUnCheck)
})
})
})
</script>
JavaScript代码相对比较简单。主要是父元素的三种状态,全选,部分选和全不选。由子元素和自己的选择变化。主要使用两个高阶函数,every和some。在处理这种问题是这两个函数非常好用。具体的效果如下;