(1)点击全选按钮, 所有选项都被选中;
(2)再次点击全选按钮, 所有选项都不被选中;
(3)当有一个选项没有被选中时, 全选按钮即不勾选。
(4)当所有的复选框都被选中时,全选按钮也自动选中
1、设置表格的css样式属性
<style>
* {
text-decoration: none;
}
table {
text-align: center;
border-collapse: collapse;
}
tr:first-of-type td:nth-of-type(2),
tr:first-of-type td:nth-of-type(3){
font-size: 25px;
font-weight: bold;
}
tr:first-of-type {
background-color: rgb(121, 185, 237);
}
tr:first-of-type td {
border: none;
}
td {
border: 2px solid #ccc;
height: 80px;
}
tr td:first-of-type {
width: 100px;
}
tr td:nth-of-type(2) {
width: 200px;
}
tr td:nth-of-type(3) {
width: 150px;
}
table input {
width: 20px;
height: 20px;
}
table a {
font-size: 20px;
color: blue;
}
</style>
2、设置表格的HTML样式
<table>
<tr>
<td><input id="allChecked" type="checkbox"> <br/> 全选/全不选</td>
<td>商品</td>
<td>单价</td>
</tr>
<tr>
<td><input class="goodsList" type="checkbox"></td>
<td><a href="">小米12</a></td>
<td><a href="">4999</a></td>
</tr>
<tr>
<td><input class="goodsList" type="checkbox"></td>
<td><a href="">小米11</a></td>
<td><a href="">3999</a></td>
</tr>
<tr>
<td><input class="goodsList" type="checkbox"></td>
<td><a href="">小米10</a></td>
<td><a href="">3999</a></td>
</tr>
<tr>
<td><input class="goodsList" type="checkbox"></td>
<td><a href="">Air</a></td>
<td><a href="">200</a></td>
</tr>
</table>
3、定义JS属性,实现复选框的各种点击效果
<script>
let goodsList = document.getElementsByClassName('goodsList'); //获取所有复选框节点
let allChecked = document.getElementById('allChecked'); //获取全选框节点
allChecked.addEventListener('click', () => { //当点击全选框时 所有商品都选中
for (let i = 0; i < goodsList.length; i++) {
goodsList[i].checked = allChecked.checked //把全选框选中状态 和所有商品选中状态绑定
}
})
let arr = []; // 定义空数组
for (let j = 0; j < goodsList.length; j++) { // 拿到所有商品的复选框节点
goodsList[j].addEventListener('click', () => { // 定义点击事件
for (let i = 0; i < goodsList.length; i++) {
// 每次循环进来都刷新数组里的元素的状态给数组中添加商品复选框的状态的值
arr.splice(i, 1, goodsList[i].checked)
//进行判断当在数组中查找不到 false时并且 数组的长度为4 说明所有商品复选框都被选中,此时将全选框改为 true
if (!arr.includes(false) && arr.length == 4) {
allChecked.checked = true;
} else { // 当在数组中找到false 并且长度为4 时 此时将全选框改为false
allChecked.checked = false;
}
}
})
}
</script>
版权声明:本文为Lou__Lan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。