<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
width:300px;
height:500px;
/* border:1px solid
margin:30px auto;
}
font:20px/2 "";
}
width:20px;
height:20px;
border:1px solid
display: inline-block;
}
background:
}
width:100%;
text-align: center;
}
width:20px;
height:20px;
border:1px solid
margin-top:30px;
}
background: skyblue;
}
</style>
</head>
<body>
<div id="cont">
<div class="box">全选<p></p></div>
<div class="box1">
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
</div>
</div>
</body>
<script>
var cont = document.querySelector('#cont');
var box = cont.querySelector('.box');
var pp = box.querySelector('p');
var box1 = cont.querySelector('.box1');
var ps = box1.querySelectorAll('p');
console.log(cont,box,pp,box1,ps);
// for(var i=0;i<ps.length;i++){
// ps[i].setColor = false;
// ps[i].onclick = function(){
// // if(this.setColor){
// // this.classList.remove('active');
// // }else{
// // this.classList.add('active');
// // }
// this.classList[this.setColor ? 'remove' : 'add']('active');
// this.setColor = ! this.setColor;
// allChoose();
// }
// }
for(var i=0;i<ps.length;i++){
ps[i].index = false;
box1.onclick = eventEnt(ps,function(){
this.classList[this.index ? 'remove' : 'add']('active');
this.index = ! this.index;
allChoose();
})
}
pp.onclick = function(){
// if(pp.className){
// // pp.className = "";
// // for(var i=0;i<ps.length;i++){
// // ps[i].classList.remove('active')
// // }
// common("","remove")
// }else{
// // pp.className = "hover";
// // for(var i=0;i<ps.length;i++){
// // ps[i].classList.add('active')
// // }
// common("hover","add")
// }
pp.className ? common("","remove") :common("hover","add");
}
function common(classname , operation){
console.log(classname)
pp.className = classname;
for(var i=0;i<ps.length;i++){
// if(operation === "add") {
// ps[i].classList.add('active')
// } else {
// ps[i].classList.remove('active')
// }
ps[i].classList[operation == "add"? "add" : "remove"]('active');
}
}
//判断如果全部背景色改变;则全选框也改变背景颜色,只要单选一个没有选中那么全选也不会选中;
//可以用数组的every方法
function allChoose(){
var newPs = [...ps].every(itmes=>itmes.index);
if(newPs){
pp.classList.add('hover');
}else{
pp.classList.remove('hover');
}
}
//[...ps] ES6新增,解析数组, 等价于["","","",""]
//所有的单选选中后,全选会选中,如果单选有一项没有选中,那么全选也不会选中;
// function allChoose(){
// var newPs = [...ps].every(itmes=>itmes.setColor);
// if(newPs){
// pp.classList.add('hover');
// }else{
// pp.classList.remove('hover');
// }
// }
//事件委托的封装
function eventEnt(achild,callback){
return function(eve){
var e = eve || window.event;
var target = e.target || e.srcElement;
for(var i=0;i<achild.length;i++){
if(target == achild[i]){
callback.call(target);
}
}
}
}
</script>
</html>