2014-02-12 90 views
1

OK,讓我重寫我的問題在其他的話,所以它看起來清晰和有趣:jsFiddle彩色文本 - 棘手

我需要colorizes文本行的純CSS解決方案顏色取決於線是奇數還是偶數。

代碼的例子是:

<div class="main"> 
    <div class="zipcode12345"> 
     <div class="myclass">red with css</div> 
     <div class="myclass">blue with css</div> 
     <div class="myclass">red with css</div> 
     <div class="myclass">blue with css</div> 
     <div class="myclass">red with css</div> 
    </div> 
    <div class="zipcode23456"> 
     <div class="myclass">blue with css</div> 
    </div> 
    <div class="zipcode90033"> 
     <div class="myclass">red with css</div> 
     <div class="myclass">blue with css</div> 
     <div class="myclass">red with css</div> 
    </div> 
    <div class="zipcode11321"> 
     <div class="myclass">blue with css</div> 
     <div class="myclass">red with css</div> 
     <div class="myclass">blue with css</div> 
     <div class="myclass">red with css</div> 
    </div> 
</div> 

是否可以用CSS製作的?如您所見@ jsFiddle,它沒有按預期着色。

所以,主要的div是「主」。 內在的div總是有格式爲「zipcodeXXXXX」的類名,如你所見。 zipcodeXXXXX的數量是可變的,myclass的數量是可變的。 但是,奇數行應始終爲紅色,偶數行應始終爲藍色。 是否存在純css解決方案?

這將是

.myclass:nth-child(2n+1){ 
color:red; 
} 
.myclass:nth-child(2n){ 
color:blue; 
} 

樣,如果我們能igonre "zipcodeXXXXX" div的,對不對?

謝謝。

+0

jsFiddle已更新至http://jsfiddle.net/xY6T3/1/,因此更清晰。謝謝。 – Haradzieniec

+0

不,對於您現有的標記結構來說這是不可能的 - 「nth-child」選擇器總是查看其父元素邊界內的元素。 (提示在_name_ ...) – CBroe

+0

這就是我花了幾個小時之後才決定在這裏問這個問題:) – Haradzieniec

回答

4

簡單地套用不同的奇/偶父元素的規則以及子元素:

div[class^="zipcode"]:nth-of-type(odd) .myclass:nth-of-type(odd), 
div[class^="zipcode"]:nth-of-type(even) .myclass:nth-of-type(even) { 
    color: red; 
} 

div[class^="zipcode"]:nth-of-type(odd) .myclass:nth-of-type(even), 
div[class^="zipcode"]:nth-of-type(even) .myclass:nth-of-type(odd) { 
    color: blue; 
} 

JSFiddle demo

+0

我不能在我的情況下編輯HTML。拉鍊是我不能改變或修改的。這就是爲什麼我正在尋找一個CSS解決方案。它存在嗎?謝謝。 – Haradzieniec

+0

@Haradzieniec我已經更新了我的答案。 :) –

+0

請更新您的JSFiddle鏈接,它鏈接到我的問題,而不是您的解決方案:)但是,似乎您找到了解決方案。讓我多試幾次:) – Haradzieniec

0

你有沒有嘗試過這樣的事情:

.myclass:nth-of-type(odd) { 
    color: red; 
} 

.myclass:nth-of-type(even) { 
    color: blue; 
} 

我只是使用了@詹姆斯·唐納利提供的代碼。

0

好吧,只爲想找到解決方案的人。

這是沒有辦法了(猜爲什麼 - 同樣的事情,與上面提到的CSS解決方案?):

jQuery(".main .myclass:nth-child(odd)").css('color', 'blue'); 

這是一個解決方案:

jQuery(".main .myclass:odd").css('color', 'blue'); 

的差額由弗雷德裏克解釋here哈米迪。