Javascript操作表格隔行变色
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script type="text/javascript"> window.onload = function () { var oTab = document.getElementById("tb1"); var oldColor = ""; /*--------------------------拓展--开始------------------------------*/ // var name = oTab.getElementsByTagName("tbody")[0].getElementsByTagName("tr")[0].getElementsByTagName("td")[1].innerHTML; /* 表格的应用 1.获取 tBodies.tHead,tFoot,rows,cells 2.各行变色 鼠标移入亮度显示 3.添加删除一行 // alert(oTab.tBodies[0].rows[0].cells[1].innerHTML); // alert(name); */ /*--------------------------拓展--结束------------------------------*/ for (var i = 0; i < oTab.tBodies[0].rows.length; i++) { oTab.tBodies[0].rows[i].onmouseover = function () { //先把之前的颜色存入到oldColor变量中 oldColor = this.style.background; this.style.background = "green"; } oTab.tBodies[0].rows[i].onmouseout = function () { //把oldColor中之前的颜色重新加上 this.style.background = oldColor; } // if (i % 2) { //隔行变色 oTab.tBodies[0].rows[i].style.background = "#CCC"; } } } </script> </head> <body> <table id="tb1" border="1" style="width: 500px;"> <thead> <tr> <td>ID</td> <td>姓名</td> <td>年龄</td> </tr> </thead> <tbody> <tr> <td>1</td> <td>Cupid</td> <td>66</td> </tr> <tr> <td>2</td> <td>Fly</td> <td>45</td> </tr> <tr> <td>3</td> <td>Sky</td> <td>23</td> </tr> <tr> <td>4</td> <td>Windy</td> <td>98</td> </tr> <tr> <td>5</td> <td>Snow</td> <td>09</td> </tr> </tbody> </table> </body> </html>