实现效果:
代码:
<!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">
<link rel="stylesheet" href="http://at.alicdn.com/t/font_3028312_jwhbry8a2fk.css">
<title>Document</title>
<style>
* {
margin: 0px;
padding: 0px;
}
table {
width: 500px;
height: 300px;
margin: 20px auto;
}
</style>
</head>
<body>
<div>
<table border="1" style="border-collapse: collapse;">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>城市</th>
<th>财富</th>
<th>性别</th>
</tr>
</thead>
<tbody class="bg">
<tr>
<td>10001</td>
<td>user-1</td>
<td>城市-1</td>
<td>82830701</td>
<td>女</td>
</tr>
<tr>
<td>10002</td>
<td>user-2</td>
<td>城市-2</td>
<td>82830702</td>
<td>男</td>
</tr>
<tr>
<td>10001</td>
<td>user-1</td>
<td>城市-1</td>
<td>82830701</td>
<td>女</td>
</tr>
<tr>
<td>10002</td>
<td>user-2</td>
<td>城市-2</td>
<td>82830702</td>
<td>男</td>
</tr>
</tbody>
</table>
</div>
</body>
<script>
var trList = document.querySelector("tbody").querySelectorAll("tr");
// 通过style行内属性来改变
for (var i = 0; i < trList.length; i++) {
if (i % 2 == 0) {
trList[i].style.backgroundColor = "pink";
} else if (i % 2 != 0) {
trList[i].style.backgroundColor = "powderblue";
}
// 鼠标划入
trList[i].onmouseover = function () {
this.bgColor = this.style.backgroundColor
this.style.backgroundColor = "wheat";
}
// 鼠标划出
trList[i].onmouseout = function () {
this.style.backgroundColor = this.bgColor;
}
}
</script>
</html>