<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>原生js实现各行变色</title> <style> *{ margin:0; padding:0; } #studentCore{ width:300px; margin:0 auto; } table{ border-collapse: collapse; } td,th{ text-align: center; padding:3px 5px; border:1px solid #ccc; } th{ background-color: lightsteelblue; } .hightLight{ background-color: pink; } </style> </head> <body > <div id="studentCore"> <table> <thead> <tr> <th>Sname</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>明明</td> <td>50</td> </tr> <tr> <td>静静</td> <td>60</td> </tr> <tr> <td>日日</td> <td>65</td> </tr> <tr> <td>李磊</td> <td>70</td> </tr> <tr> <td>韩梅梅</td> <td>75</td> </tr> <tr> <td>杨幂</td> <td>80</td> </tr> <tr> <td>范冰冰</td> <td>85</td> </tr> </tbody> </table> </div> <script src="js/jquery-3.2.1.min.js"></script> <!--方法一--> <script> var data=document.getElementById("studentCore"); var trs=data.querySelectorAll("tbody>tr"); console.log(trs); for (var i=0;i<trs.length;i++){ i%2!=0&&(trs[i].className="hightLight"); } </script> <!--方法二--> <script> function setTableColor() { var data=document.getElementById("studentCore"); var trs=data.getElementsByTagName("tr"); for(var i=0;i<trs.length;i++){ var j=i+1; if(j%2==0){ trs[i].style.background="pink"; }else{ trs[i].style.background="yellow"; } } } setTableColor(); </script> </body> </html>
时间: 2024-12-20 14:37:12