以前以为Table隔行变色只能通过js和后台逻辑代码实现,但是今天帮同事处理Table隔行变色时发现css里面也能写逻辑代码:

直接上代码(复制到本地运行查看效果):

 

 
   
  1. <html> 
  2. <head> 
  3. <title>Table隔行变色</title> 
  4. <style> 
  5. <!-- 
  6.     tr{ 
  7.         background: #f00; 
  8.     } 
  9.     tr:nth-child(2n){ 
  10.         background: #ccc; 
  11.     } 
  12.     tr{ 
  13.         background-color: expression((this.sectionRowIndex % 2 == 0) ?   "#f00" : "#ccc" ); 
  14.     } 
  15. --> 
  16. </style> 
  17. </head> 
  18. <body> 
  19. <table> 
  20.     <tr><td>111111111</td></tr> 
  21.     <tr><td>222222222</td></tr> 
  22.     <tr><td>333333333</td></tr> 
  23.     <tr><td>444444444</td></tr> 
  24. </table> 
  25. </body> 
  26. </html> 
  27.  
  28. /***********************下面是js实现的(附加 对比下)********************/ 
  29.  
  30. <html> 
  31. <head> 
  32. <title>隔行变色的鼠标经过变色</title> 
  33. <style type="text/css" media="screen"> 
  34. table {border-collapse:collapse;border:solid #999;border-width:1px 0 0 1px;} 
  35. table td {border:solid #999;border-width:0 1px 1px 0;} 
  36. .t1 {background-color:#fff;} 
  37. .t2 {background-color:#eee;} 
  38. .t3 {background-color:#ccc;} 
  39. </style> 
  40. <script type="text/javascript"> 
  41. var Ptr=document.getElementsByTagName("tr"); 
  42. function recolor() { 
  43. for (i=1;i<Ptr.length+1;i++) { 
  44. Ptr[i-1].className = (i%2>0)?"t1":"t2"; 
  45. window.onload=recolor
  46. for(var i=0;i<Ptr.length;i++) { 
  47. Ptr[i].onmouseover=function(){ 
  48. thisthis.tmpClass=this.className; 
  49. this.className = "t3"
  50. }; 
  51. Ptr[i].onmouseout=function(){ 
  52. thisthis.className=this.tmpClass; 
  53. }; 
  54. </script> 
  55. </head> 
  56.  
  57. <body> 
  58. <table width=400 align=center> 
  59. <tr><td>1</td><td>2</td></tr> 
  60. <tr><td>1</td><td>2</td></tr> 
  61. <tr><td>1</td><td>2</td></tr> 
  62. <tr><td>1</td><td>2</td></tr> 
  63. </table> 
  64. </body> 
  65. </html>