1.Html和JavaScript
<table>
<tr>
<th class="allCheck">
<input type="checkbox" name="" id="checkAll"> <span class="all">全选</span>
</th>
<th>商品</th>
<th>商家</th>
<th>价格</th>
</tr>
<tr>
<td>
<input type="checkbox" name="check" class="ck">
</td>
<td>小米手机</td>
<td>小米</td>
<td>¥1999</td>
</tr>
<tr>
<td>
<input type="checkbox" name="check" class="ck">
</td>
<td>苹果手机</td>
<td>苹果</td>
<td>¥6999</td>
</tr>
<tr>
<td>
<input type="checkbox" name="check" class="ck">
</td>
<td>华为手机</td>
<td>华为</td>
<td>¥6999</td>
</tr>
</table>
<script>
//1.获取大复选框
const checkAll = document.querySelector('#checkAll')
//2.获取所有的小复选框
const cks = document.querySelectorAll('.ck')
//3.点击大复选框 注册事件
checkAll.addEventListener('click',function(){
// console.log(this.checkAll);
//4.遍历所有的小复选框,让小复选框的checked = 大复选框的checked
for(let i = 0;i < cks.length;i++){
// cks[i].checked = checkAll.checked
cks[i].checked = this.checked
}
//5.小复选框控制大复选框
for(let i = 0; i< cks.length;i++){
//5.1给所有的小复选框添加点击事件
cks[i].addEventListener('click',function(){
//判断选中的小复选框个数 是不是等于 总的小复选框个数
//等于3就全选
checkAll.checked = document.querySelectorAll('.ck:checked').length === cks.length
})
}
})
</script>
2.CSS样式
<style>
* {
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #c0c0c0;
width: 900px;
margin: 100px auto;
text-align: center;
}
th {
background-color: #09c;
font: bold 16px "微软雅黑";
color: #fff;
height: 24px;
}
td {
border: 1px solid #d0d0d0;
color: #404060;
padding: 10px;
}
.allCheck {
width: 80px;
}
</style>