1. 思路
- 用到的事件:mouseover(鼠标经过)、mouseout(鼠标离开);
- 鼠标经过tr行,当前行背景变色,鼠标离开背景颜色恢复;
- 注意:thead中的行无需变色,只需要操作tobody中的行即可;
2. 代码
2.1 html
<table>
<thead>
<tr>
<th>姓名</th>
<th>学号</th>
<th>班级</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>001</td>
<td>1年1班</td>
</tr>
<tr>
<td>李四</td>
<td>002</td>
<td>1年2班</td>
</tr>
<tr>
<td>王五</td>
<td>004</td>
<td>5年1班</td>
</tr>
</tbody>
</table>
2.2 css
<style>
table{
width: 800px;
margin: 100px auto;
text-align: center;
border-collapse: collapse;
font-size: 14px;
}
thead tr {
height: 30px;
background-color: skyblue;
}
tbody tr {
height: 30px;
}
tbody td {
border-bottom: 1px solid #d7d7d7;
font-size: 12px;
color: blue;
}
.bg{
background-color: purple;
}
</style>
2.3 js
<script>
var trs = document.querySelector('tbody').querySelectorAll('tr');
for (var i=0; i<trs.length; i++) {
trs[i].onmouseover = function() {
this.className = 'bg';
}
trs[i].onmouseout = function() {
this.className = '';
}
}
</script>
2.4 效果
- 鼠标悬浮
- 鼠标离开