题目:鼠标经过表单中的行,行变色
分析:
1. 用到新的鼠标事件 鼠标经过onmouseover 鼠标离开onmouseout;
2. 核心思路:鼠标经过tr 行,当前行变换背景颜色,因此我们获取的是tbody里面的行;
3. 注意:第一行(thead里面的行) 不需要变换颜色,因此我们获取的是tbody 里面的行。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
width: 800px;
margin: 100px auto;
text-align: center;
border-collapse: collapse;
font-size: 14px;
}
thead tr {
height: 30px;
background-color: rgb(92, 193, 54);
}
tbody tr {
height: 30px;
}
tbody td {
border-bottom: 1px solid yellowgreen;
font-size: 12px;
color: darkgreen;
}
.bg {
background-color: darkseagreen;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>代码</th>
<th>名称</th>
<th>净值</th>
<th>累计</th>
<th>前单位</th>
<th>增长率</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>西兰花</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26%</td>
</tr>
<tr>
<td>002</td>
<td>西红柿</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26%</td>
</tr>
<tr>
<td>003</td>
<td>马铃薯</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26%</td>
</tr>
<tr>
<td>004</td>
<td>奇异果</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26%</td>
</tr>
</tbody>
</table>
<script>
// 1. 获取tbody 里的所有行
var trs = document.querySelector('tbody').querySelectorAll('tr');
// console.log(trs);
// 2. 循环注册事件
for (var i = 0; i < trs.length; i++) {
// 鼠标经过更换背景
trs[i].onmouseover = function () {
// console.log(11);
this.className = 'bg';
}
// 鼠标离开背景初始化
trs[i].onmouseout = function () {
this.className = '';
}
}
</script>
</body>
</html>