JS应用实例4:表格隔行换色

HTML代码:

<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title>表格隔行换色</title>
<script>
window.onload = function() {
//1.获取表格
var tblEle = document.getElementById("tbl");
//2.获取表格中tbody里面的行数(长度)
var len = tblEle.tBodies[0].rows.length;
//3.对tbody里面的行进行遍历
for(var i = 0; i < len; i++) {
if(i % 2 == 0) {
//4.对偶数行设置背景颜色
tblEle.tBodies[0].rows[i].style.backgroundColor = "blue";
} else {
//5.对奇数行设置背景颜色
tblEle.tBodies[0].rows[i].style.backgroundColor = "gold";
}
}
}
</script> </head> <body>
<table border="1" width="500" height="50" align="center" id="tbl">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>张三</td>
<td>22</td>
</tr>
<tr>
<td>2</td>
<td>李四</td>
<td>25</td>
</tr>
<tr>
<td>3</td>
<td>王五</td>
<td>27</td>
</tr>
<tr>
<td>4</td>
<td>小明</td>
<td>29</td>
</tr>
<tr>
<td>5</td>
<td>小红</td>
<td>30</td>
</tr>
<tr>
<td>6</td>
<td>小刚</td>
<td>20</td>
</tr>
</tbody>
</table>
</body> </html>

效果:

JS应用实例4:表格隔行换色

表格高亮显示:

<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title>表格隔行换色</title>
<script>
function changeColor(id, flag) {
if(flag == "over") {
document.getElementById(id).style.backgroundColor = "red";
} else if(flag == "out") {
document.getElementById(id).style.backgroundColor = "yellow";
}
}
</script> </head> <body>
<table border="1" width="500" height="50" align="center">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr onmouseover="changeColor('tr1','over')" id="tr1" onmouseout="changeColor('tr1','out')">
<td>1</td>
<td>张三</td>
<td>22</td>
</tr>
<tr onmouseover="changeColor('tr2','over')" id="tr2" onmouseout="changeColor('tr2','out')">
<td>2</td>
<td>李四</td>
<td>25</td>
</tr>
<tr onmouseover="changeColor('tr3','over')" id="tr3" onmouseout="changeColor('tr3','out')">
<td>3</td>
<td>王五</td>
<td>27</td>
</tr>
<tr onmouseover="changeColor('tr4','over')" id="tr4" onmouseout="changeColor('tr4','out')">
<td>4</td>
<td>小明</td>
<td>29</td>
</tr>
<tr onmouseover="changeColor('tr5','over')" id="tr5" onmouseout="changeColor('tr5','out')">
<td>5</td>
<td>小红</td>
<td>30</td>
</tr>
<tr onmouseover="changeColor('tr6','over')" id="tr6" onmouseout="changeColor('tr6','out')">
<td>6</td>
<td>小刚</td>
<td>20</td>
</tr>
</tbody>
</table>
</body> </html>

效果:

鼠标移到上面变成红色,移开变成黄色,不移动时候没有颜色

JS应用实例4:表格隔行换色

上一篇:while和do-while语句的异同之处


下一篇:在linux中,我为什么不能安装VMware Tools?