JS中table隔行换色
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <table id="tab1" border="" cellspacing="" cellpadding="" width="40%"> 9 <thead> 10 <tr> 11 <td>ID</td> 12 <td>姓名</td> 13 <td>年龄</td> 14 </tr> 15 </thead> 16 <tbody> 17 <tr> 18 <td>1</td> 19 <td>张三</td> 20 <td>27</td> 21 </tr> 22 <tr> 23 <td>2</td> 24 <td>李四</td> 25 <td>20</td> 26 </tr> 27 <tr> 28 <td>3</td> 29 <td>张可爱</td> 30 <td>29</td> 31 </tr> 32 <tr> 33 <td>4</td> 34 <td>李XX</td> 35 <td>24</td> 36 </tr> 37 <tr> 38 <td>5</td> 39 <td>马小关</td> 40 <td>35</td> 41 </tr> 42 </tbody> 43 </table> 44 </body> 45 <script type="text/javascript"> 46 window.onload = function(){ 47 48 var oTab = document.getElementById("tab1"); 49 var oldColor = ""; 50 //鼠标移到单元格上变色 51 for(var i=0;i<oTab.tBodies[0].rows.length;i++){ 52 53 oTab.tBodies[0].rows[i].onmouseover=function(){ 54 oldColor = this.style.background; 55 this.style.background = "yellow"; 56 } 57 58 oTab.tBodies[0].rows[i].onmouseout=function(){ 59 this.style.background = oldColor; 60 } 61 62 //实现各行换色 63 if(i%2==0){ 64 oTab.tBodies[0].rows[i].style.background = "#ccc"; 65 }else{ 66 oTab.tBodies[0].rows[i].style.background = ""; 67 } 68 69 } 70 } 71 </script> 72 </html>
时间: 2024-10-03 19:13:59