案例展示
分析
html与css部分不做描述,依个人喜好进行设计,主要还是js实现功能。
- 事件三要素:事件源 、事件类型 、事件处理程序
- 鼠标悬浮(
onmouseover
)、鼠标离开(onmouseleave
)、鼠标点击(onclick
)事件 - 排他思想:所有元素全部清除之后设置当前元素
- 头部复选框与表格内复选框的逻辑关系
1.点击头部复选框,表格内所有复选框全选(全不选)
2.点击表内复选框,只要有一个没选,则头部复选框不被选择,否则头部选中。
代码实现
css部分
.table {
width: 700px;
padding: 20px;
text-align: left;
border: 1px solid #ccc;
margin: 20px auto;
box-sizing: border-box;
}
table {
width: 680px;
}
input {
margin-left: 10px;
}
tbody {
padding: 10px;
box-sizing: border-box;
}
tr {
/* width: 700px; */
width: 95%;
height: 40px;
line-height: 40px;
padding-left: 20px;
border-bottom: 1px solid #ccc;
background-color: transparent;
box-sizing: border-box;
}
html部分:
<div class="table">
<table>
<thead>
<th>
<input type="checkbox" class="all">
</th>
<th>日期</th>
<th>姓名</th>
<th>地址</th>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" class="check">
</td>
<td>
2016-06-03
</td>
<td>王小虎</td>
<td>上海市普陀区金沙江路 1518 弄</td>
</tr>
<tr>
<td>
<input type="checkbox" class="check">
</td>
<td>
2016-06-03
</td>
<td>王小虎</td>
<td>上海市普陀区金沙江路 1518 弄</td>
</tr>
<tr>
<td>
<input type="checkbox" class="check">
</td>
<td>
2016-06-03
</td>
<td>王小虎</td>
<td>上海市普陀区金沙江路 1518 弄</td>
</tr>
</tbody>
</table>
</div>
JavaScript部分
<script>
var trs = document.getElementsByTagName('tr')
var all = document.querySelector('.all')
var check = document.querySelectorAll('.check')
var flag = true;
console.log(check)
for (const keys in trs) {
trs[keys].onmouseover = function () {
this.style.backgroundColor = '#F5F7FA'
}
trs[keys].onmouseleave = function () {
this.style.backgroundColor = 'transparent'
}
}
all.onclick = function () {
if (flag) {
for (const key in check) {
check[key].checked = true;
}
} else {
for (const key in check) {
check[key].checked = false;
}
}
flag = !flag
}
for (var i = 0;i<check.length;i++) {
check[i].onclick = function () {
var flags = true;
for (var i = 0; i < check.length; i++) {
if (!check[i].checked) {
flags = false;
console.log('执行');
break;
}
}
all.checked = flags;
}
}
</script>