全选,多选,单选

Original 2019-03-03 09:34:34 277
abstract:<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0&qu
<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>全选</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}

body {
font-family: "Microsoft YaHei";
}

ul,
li {
list-style: none;
}

.box {
width: 140px;
overflow: auto;
border: solid 1px #333;
margin: 0 auto;
}

#all,
.one {
width: 120px;
height: 40px;
box-sizing: border-box;
margin: 0 auto;
position: relative;
}

#all {
border-bottom: solid 1px #666;
}

.btn {
width: 12px;
height: 12px;
border: solid 1px #999;
position: absolute;
top: 12px;
left: 7px;
cursor: pointer;
}

.btn.on {
background: #333;
}

#all p,
.one p {
position: absolute;
line-height: 40px;
top: 0;
left: 30px;
}
</style>

<body>
<div class="box">
<div id="all">
<div class="btn"></div>
<p>全选</p>
</div>
<div class="one">
<div class="btn"></div>
<p>食物</p>
</div>
<div class="one">
<div class="btn"></div>
<p>服装</p>
</div>
<div class="one">
<div class="btn"></div>
<p>家具</p>
</div>
<div class="one">
<div class="btn"></div>
<p>房屋</p>
</div>
<div class="one">
<div class="btn"></div>
<p>汽车</p>
</div>
</div>
<script>
(function () {
var oAll = document.getElementById('all'),
aOne = document.getElementsByClassName('one'),
aBtn = document.getElementsByClassName('btn');
var oBool = false,
idx = 0;
oAll.children[0].onclick = function () {
for (let i = 0; i < aBtn.length; i++) {
if (!oBool) {
aBtn[i].classList.add("on");
idx = 5;
} else {
aBtn[i].classList.remove("on");
idx = 0;
}
}
oBool = !oBool;
}
for (let j = 0; j < aOne.length; j++) {
aOne[j].children[0].onclick = function () {
if (aBtn[j + 1].getAttribute('class')) {
if (aBtn[j + 1].getAttribute('class').indexOf('on') > -1) {
aBtn[j + 1].classList.remove("on");
idx = (idx - 1);
} else {
aBtn[j + 1].classList.add("on");
idx = (idx + 1);
}
}
if (idx < 5) {
aBtn[0].classList.remove("on");
oBool = false;
} else {
aBtn[0].classList.add("on");
oBool = true;
}
}

}
})();
</script>
</body>

</html>

注意逻辑关系,多用控制台console

Correcting teacher:西门大官人Correction time:2019-03-03 10:50:36
Teacher's summary:代码写的比较复杂,最好加一下必要的注释。

Release Notes

Popular Entries