2013-04-18 35 views
0

我有備用行背景色的表:與例外其他行>繼承背景顏色

tr:nth-child(even) {background: #FFF} 
tr:nth-child(odd) {background: #f4f4f4} 

該表是由兩種類型的細胞,「主要」和「.SUB」的。

我想背景顏色交替其他所有「。主」,而所有「.SUB」行獲得前一個「。主」的顏色。

如果解決方案都是CSS,但是如果它真的是最好的選擇,那麼對jquery開放會很棒。

任何想法?

<table> 
    <tr id='1' class='main'><td></td></tr> 
    <tr id='2' class='main'><td></td></tr> 
    <tr id='3' class='main'><td></td></tr> 
    <tr id='4' class='main'><td></td></tr> 
    <tr id='5' class='main'><td></td></tr> 
    <tr id='6' class='sub'><td></td></tr> 
    <tr id='7' class='main'><td></td></tr> 
    <tr id='8' class='main'><td></td></tr> 
    <tr id='9' class='sub'><td></td></tr> 
    <tr id='10' class='sub'><td></td></tr> 
    <tr id='11' class='main'><td></td></tr> 
</table> 

行1,3,5,8應該是#f4f4f4

行2,4,7,11應#fffff

並且每個.SUB行應的顏色相同前面的.main行。

(這些表是動態生成的,所以他們的位置會發生變化)

編輯: 這裏是用jQuery 我失敗的第一次嘗試http://jsfiddle.net/xjDZm/

+0

你介意提供一個示例HTML或更好的提供[小提琴](http://jsfiddle.net)? – Passerby

+0

這裏是一個簡單的HTML示例。我會盡力爭取一秒鐘的小提琴。謝謝! – dsol828

+0

小提琴添加到OP ...這是我失敗的第一次嘗試使用jquery – dsol828

回答

1

我不想到的jsfiddle這是可能的純CSS,你似乎需要的款式奇數行的.main,不是奇數行.main,並:nth-child不能這樣做,(你不能使用(tr.main):nth-child(odd),更何況你requi與.sub rement更加複雜)。

因此,這裏是一個jQuery的解決方案:

$("tr.main").filter(":even").css("background-color","#CCC");//change to #F4F4F4 
$("tr.main").filter(":odd").css("background-color","#FFF"); 
$("tr.sub").each(function(i,e){ 
    $(this).css("background-color",$(this).prev().css("background-color")); 
}); 

http://jsfiddle.net/xjDZm/1/

對不起,我不使用jQuery,所以我不知道是否有代碼什麼更好的辦法。我只是查找API文檔來查找可行的方法。

+0

謝謝!我不知道爲什麼我無法正確使用jquery。在jQuery級別過濾似乎有訣竅! – dsol828