方法1:原生JavaScript
设置CSS
table td{ border:red solid 1px; } .tr1{ color:white; background: black; } .tr2{ color:black; background: white; } .tr2:hover{ color:red; background: yellow; }
设置JavaScript
(1)获取tr标签
var ctr=document.getElementById("tab").getElementsByTagName("tr");
(2)使用循环
function fun(){ for(i=0;i<ctr.length;i++){ ctr[i].className=((i+1)%2>0)?"tr1":"tr2"; } }
(3)调用js
window.onload=fun;
注意事项:该JavaScript代码需要在
加载完毕后执行。点击查看完整代码
<!doctype html> <html> <head> <meta charset="utf-8"> <title>index</title> <style> table td{ border:red solid 1px; } .tr1{ color:white; background: black; } .tr2{ color:black; background: white; } .tr2:hover{ color:red; background: yellow; } </style> </head> <body> <table id="tab"> <tr> <td>mllt</td> <td>mllt</td> <td>mllt</td> </tr> <tr> <td>mllt</td> <td>mllt</td> <td>mllt</td> </tr> <tr> <td>mllt</td> <td>mllt</td> <td>mllt</td> </tr> <tr> <td>mllt</td> <td>mllt</td> <td>mllt</td> </tr> <tr> <td>mllt</td> <td>mllt</td> <td>mllt</td> </tr> <tr> <td>mllt</td> <td>mllt</td> <td>mllt</td> </tr> <tr> <td>mllt</td> <td>mllt</td> <td>mllt</td> </tr> <tr> <td>mllt</td> <td>mllt</td> <td>mllt</td> </tr> <tr> <td>mllt</td> <td>mllt</td> <td>mllt</td> </tr> <tr> <td>mllt</td> <td>mllt</td> <td>mllt</td> </tr> </table> </body> <script> var ctr=document.getElementById("tab").getElementsByTagName("tr"); function fun(){ for(i=0;i<ctr.length;i++){ ctr[i].className=((i+1)%2>0)?"tr1":"tr2"; } } window.onload=fun; </script> </html>