<分区>
Possible Duplicate:
Sorting a set of CSS selectors on the basis of specificity
我需要一个 JS 库,它可以将 CSS 选择器文本从最具体的选择器文本排序到不太具体的选择器文本,其中根据 W3C 指定特异性。
如果那里没有任何库,我可以使用 JS 或 jQuery 简单地编写它吗?
CSS 选择器文本可以是 div#body .text
。
<分区>
Possible Duplicate:
Sorting a set of CSS selectors on the basis of specificity
我需要一个 JS 库,它可以将 CSS 选择器文本从最具体的选择器文本排序到不太具体的选择器文本,其中根据 W3C 指定特异性。
如果那里没有任何库,我可以使用 JS 或 jQuery 简单地编写它吗?
CSS 选择器文本可以是 div#body .text
。
最佳答案
在对您的问题的评论中,josh3736 链接 the W3C specification for determining specificity .如果您想要自己编写这样一个库(我鼓励您这样做,只是为了更多地了解它),他们的方法似乎是一个很好的引用。
A selector's specificity is calculated as follows:
- count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
- count the number of ID attributes in the selector (= b)
- count the number of other attributes and pseudo-classes in the selector (= c)
- count the number of element names and pseudo-elements in the selector (= d)
The specificity is based only on the form of the selector. In particular, a selector of the form "[id=p33]" is counted as an attribute selector (a=0, b=0, c=1, d=0), even if the id attribute is defined as an "ID" in the source document's DTD.
Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.
关于javascript - 是否有一个 JS 库可以根据特异性对 CSS 选择器文本进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11181322/