2014/08/17
sample(jQueryを使う方法)
sample2(CSS3を使う方法)
どちらの方法を使う場合も一行おきに背景色を変えるtableタグにlinecoloredというクラスをつけておくと都合が良いかもしれない。
<table class="linecolored"><table>
<tr>
<th>111</th><th>222</th><th>333</th><th>444</th>
</tr>
<tr>
<td>AAA</td><td>BBB</td><td>CCC</td><td>DDD</td>
</tr>
<tr>
<td>AAA</td><td>BBB</td><td>CCC</td><td>DDD</td>
</tr>
</tbody></table>
jQueryではtrに0,1,2,3,...と順が振られるので、偶数行のtrタグにcoloredというクラスを加え、これに応じてCSSでcolored付いたクラスのtrに背景色を着けることになる。
<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script> <script type="text/javascript"> $(function() { $(".linecolored tr:even").addClass("colored"); //偶数行にcoloredクラスを加える }); </script>
table.linecolored tr { background-color:#fff; } table.linecolored tr.colored { background-color:#eee; } table.linecolored .th { background-color:#ccc; }
CSSではnth-child擬似要素を使うが、jQueryと違ってtrに1,2,3と順が振られるので奇数行に背景色を着けることになる。
こちらの方が簡単だがIE8はCSS3非対応なので一工夫が要る。
table.linecolored tr { background-color:#fff; } table.linecolored tr:nth-child(odd){ background-color:#eee;/*奇数行oddにカラーを指定する*/ } table.linecolored th { background-color:#ccc; }
IE8でもnth-child()が効くようにIE9.jsを読み込んでおく。
<!--[if lt IE 9]> <script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script> <![endif]-->
Ida Qitailang