javascript - 是否有一个 JS 库可以根据特异性对 CSS 选择器文本进行排序?

标签 javascript jquery css css-selectors css-specificity

<分区>

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/

相关文章:

jquery - 通过 CSS 制作 HTML 月日日期今天星期

javascript - jquery 验证瑞典语字符

html - 文本溢出 Div 使用变换时 : rotate(90. 0deg)

css - 覆盖 body 属性

javascript - 正则表达式匹配是否包含彼此相邻的相同字符 0 或 2 或 4 次

javascript - 使用Jquery控制动态生成的HTML

javascript - 针对安卓移动设备

javascript - 将数字转换为尽可能短的字符串,同时保持唯一性

jquery - 突出显示当前页面的两级水平菜单

html - DIV 未采用 100% 视口(viewport)高度