2014年4月7日 星期一

【CSS】:nth-child v.s. jQuery:eq

之前沒研究清楚,
誤以為 CSS's :nth-child  跟 jQuery's :eq
兩者的 selector 是相同效果,
但其實這兩者之間定義不完全相同。

先來看看 jQuery's :eq( index ) 的定義,
Reduce the set of matched elements to the one at the specified index.
如果 index 為正值,則是以 0 對映到首個element;
   index 為負值,則從最後一個element計數。

再來看看 CSS's :nth-child( n ) 的定義,
The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.
n can be a number, a keyword, or a formula.
差異在於 CSS 會先找其parent的所有child element,再判斷是否符合條件。

舉例而言:
<div>
    <p>This is a heading</p>
    <div id="one" class="foo"></div>
    <div id="two" class="foo"></div>
    <div id="three" class="foo"></div>
</div>
以CSS Syntax來講, .foo:nth-child(2) 會找到 div#one ,
因為 #one 是容器內第二個元素,類別也符合條件。
但若 .foo:nth-child(1) 則找不到符合的元素,
因為容器內第一個元素是 p tag ,但卻不符合類別的條件。
補充 jQuery's :nth-child 定義,
Selects all elements that are the nth-child of their parent.
另外 jQuery's implementation of :nth- selectors is strictly derived from the CSS specification
所以 jQuery's :eq 只回傳第一個符合條件的元素;
而 jQuery's :nth-child 則會回傳所有符合條件的元素。

沒有留言:

張貼留言