2014-07-03 96 views
3

我要讓li元素交替的顏色,但只有那些具有屬性替代顏色申請,但只有那些元素data-filetype="image".如何具有特定數據屬性

只要我添加了一個新的li無需添加data-filetype attribute,我的顏色序列失敗。

鏈接JSBin是here

HTML代碼:

<ul> 
<li data-filetype="image">PNG Image</li><!-- It should be RED --> 
<li data-filetype="image">PNG Image</li><!-- It should be ORANGE --> 
<li>Normal Link</li><!-- After adding this li color sequence breaks --> 
<li data-filetype="image">PNG Image</li><!-- It should be RED --> 
<li data-filetype="image">PNG Image</li><!-- It should be ORANGE --> 
</ul> 

CSS:

ul li[data-filetype="image"]:nth-child(2n){color:orange} 
ul li[data-filetype="image"]:nth-child(2n+1){color:red} 
+0

但沒有任何替代辦法? –

+0

不要用純CSS來這麼想 – Pete

+1

不,你不能用CSS來做這種事情,因爲只適用於元素(具有共同的父元素)並且與類沒有關係或任何其他屬性。請參閱 - http://stackoverflow.com/questions/5428676/nth-child-doesnt-respond-to-class –

回答

0

使用jQuery你可以得到即使額外的元素添加備用行顏色。看看DEMO

/jQuery代碼/

$(document).ready(function(){ 

$("li[data-filetype='image']:even").css({'color':'red'}); 
$("li[data-filetype='image']:odd").css({'color':'blue'}); 
$("li:not([data-filetype='image'])").css({'color':'white'}); 
}); 
+0

它適合你嗎? –

+0

這可行,但我正在尋找CSS解決方案。現在的問題是,如果它通過JQuery工作,那麼爲什麼它不能只使用CSS。 –