主要是用遍历的方法查找元素,然后通过改变checked的属性来选择,为true则是选中状态,为false则是未选状态
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>复选框的选择</title>
<style>
.container {
width: 310px;
margin: 0 auto;
}
#btn {
margin: 20px auto;
}
#btn>input {
font-size: 16px;
color: #fff;
background-color: rgb(0, 153, 255);
outline: none;
border: none;
cursor: pointer;
width: 100px;
height: 32px;
line-height: 32px;
border-radius: 4px;
}
#btn>input:hover {
opacity: 0.6;
}
#city {
background-color: rgb(221, 221, 221);
color: #333;
padding: 8px;
border-radius: 4px;
font-size: 16px;
font-weight: 500;
line-height: 32px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<div id="btn">
<input type="button" id="btn1" value="全选">
<input type="button" id="btn2" value="全不选">
<input type="button" id="btn3" value="反选">
</div>
<div id="city">
<input type="checkbox">北京<br>
<input type="checkbox">上海<br>
<input type="checkbox">广州<br>
<input type="checkbox">深圳<br>
</div>
</div>
<script>
window.onload = function () {
var obt1 = document.getElementById('btn1');
var obt2 = document.getElementById('btn2');
var obt3 = document.getElementById('btn3');
var city = document.getElementById('city');
var value = city.getElementsByTagName('input');
obt1.onclick = function () {
for (var i = 0; i < value.length; i++) {
value[i].checked = true;
}
}
obt2.onclick = function () {
for (var i = 0; i < value.length; i++) {
value[i].checked = false;
}
}
obt3.onclick = function () {
for (var i = 0; i < value.length; i++) {
if (value[i].checked == false) {
value[i].checked = true;
} else {
value[i].checked = false;
}
}
}
}
</script>
</body>
</html>