2011-02-23 72 views
5

當我迭代集合時,是否有可能僅使用CSS爲動態生成的表格設置奇數行和偶數行上的不同樣式,而無需在每行上設置正確樣式?奇數和偶數行上的不同CSS樣式

+1

看到這裏的'第n-child'示範答案:http://stackoverflow.com/questions/5080699/using-css-even-and-odd-pseudo-selectors-with-list-items – thirtydot 2011-02-23 20:10:01

+0

你不應該混淆Java和JavaScript(它被重新授權給你)。請參閱:http://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java – thirtydot 2011-02-23 20:16:09

+0

jQuery的+1,它存在的一個原因,真的沒有任何有效的理由不使用它如果你使用JavaScript開始。 – 2011-02-24 03:01:45

回答

10

我不知道這會工作的跨瀏覽器使用jquery,我寧願jQuery的自己,但CSS-只有這應該做的伎倆:

tr:nth-child(even) { ... } 
tr:nth-child(odd) { ... } 
+4

嗯,這是跨瀏覽器的瀏覽器不吸吮... – 2011-02-23 23:13:03

2

你可以用CSS3做到這一點。

tr:nth-child(2n+1) /* targets all odd rows */ 
tr:nth-child(2n) /* targets all even rows */ 
1

,你可以簡單地使用jQuery和喜歡

$("tr:nth-child(odd)").addClass("odd"); 

和樣式使用CSS將其添加類奇數行作爲

.odd{background-color:#657383}