用 jQuery 做表格斑馬紋時,一定會碰到 :nth-child(even)。既然遇上了,不如把 CSS3 這個偽類選擇器的用法一次弄懂。
參數必須是大於 0 的整數。
li:nth-child(3){background:orange;} /* 把第 3 個 LI 背景設為橙色 */
字母 n 不能省,它是「倍數寫法」的標記,例如 3n、5n。
li:nth-child(3n){background:orange;} /* 第 3、6、9…所有 3 的倍數 */
把元素每 a 個分一組,b 是組內的序號。n 與正負號不可缺省、位置不可調換,a、b 為正整數或 0。
li:nth-child(3n+1){background:orange;} /* 第 1、4、7…每 3 個一組的第 1 個 */
li:nth-child(3n+5){background:orange;} /* 第 5、8、11… */
li:nth-child(5n-1){background:orange;} /* 第 4、9、14… */
li:nth-child(3n±0){background:orange;} /* 等同 3n */
li:nth-child(±0n+3){background:orange;} /* 等同 3 */
一負一正,兩者都不可缺省,否則沒有意義。它從第 b 個往前回算,所以匹配到的數量最多不會超過 b 個。
li:nth-child(-3n+8){background:orange;} /* 第 8、5、2 個 */
li:nth-child(-1n+8){background:orange;} /* 亦可寫成 (-n+8),前 8 個 */
其中 -n+8 特別實用,想限定「只作用於前 N 個」時經常派上用場。(an 前面也可以帶負號,那留到下一節再談。)
odd 選奇數、even 選偶數。odd 等同 2n+1;even 等同 2n+0 也就是 2n。
$("table tr:nth-child(even)").addClass("striped");
even 可以替換成前面介紹的五種任一寫法,後面的 addClass("striped") 只是掛上一個 CSS class,實際配色寫在樣式表裡。
本來只是為了學 jQuery,順手把 CSS 選擇器也複習了一遍,算是意外的收穫。