以前以为Table隔行变色只能通过js和后台逻辑代码实现,但是今天帮同事处理Table隔行变色时发现css里面也能写逻辑代码:
直接上代码(复制到本地运行查看效果):
- <html>
- <head>
- <title>Table隔行变色</title>
- <style>
- <!--
- tr{
- background: #f00;
- }
- tr:nth-child(2n){
- background: #ccc;
- }
- tr{
- background-color: expression((this.sectionRowIndex % 2 == 0) ? "#f00" : "#ccc" );
- }
- -->
- </style>
- </head>
- <body>
- <table>
- <tr><td>111111111</td></tr>
- <tr><td>222222222</td></tr>
- <tr><td>333333333</td></tr>
- <tr><td>444444444</td></tr>
- </table>
- </body>
- </html>
- /***********************下面是js实现的(附加 对比下)********************/
- <html>
- <head>
- <title>隔行变色的鼠标经过变色</title>
- <style type="text/css" media="screen">
- table {border-collapse:collapse;border:solid #999;border-width:1px 0 0 1px;}
- table td {border:solid #999;border-width:0 1px 1px 0;}
- .t1 {background-color:#fff;}
- .t2 {background-color:#eee;}
- .t3 {background-color:#ccc;}
- </style>
- <script type="text/javascript">
- var Ptr=document.getElementsByTagName("tr");
- function recolor() {
- for (i=1;i<Ptr.length+1;i++) {
- Ptr[i-1].className = (i%2>0)?"t1":"t2";
- }
- }
- window.onload=recolor;
- for(var i=0;i<Ptr.length;i++) {
- Ptr[i].onmouseover=function(){
- thisthis.tmpClass=this.className;
- this.className = "t3";
- };
- Ptr[i].onmouseout=function(){
- thisthis.className=this.tmpClass;
- };
- }
- </script>
- </head>
- <body>
- <table width=400 align=center>
- <tr><td>1</td><td>2</td></tr>
- <tr><td>1</td><td>2</td></tr>
- <tr><td>1</td><td>2</td></tr>
- <tr><td>1</td><td>2</td></tr>
- </table>
- </body>
- </html>