我已经解析了一个给定的CSS文件/字符串转换成JSON对象,像这样:
{
"#header": {
"color": "#000000"
},
"#header h1": {
"color": "#000"
},
"h1": {
"color": "#4fb6e5"
}
}
我想现在要做的是他们基于Specificty重新排序。 在这种情况下, #header h1
应该来后h1
的JSON对象,因为这是他们如何会在浏览器中使用。
我怎样才能做到这一点? 有没有这方面的任何现有的库? 或任何有用的库,以帮助这个?
我可以同时使用使用Javascript / jQuery的或PHP来做到这一点。 我要找的实施意见,并希望这个已经做了!
简短的答案:
有没有这方面的任何现有的库?
不,不是一个我所知道的,做这种“乱用”的为您服务。
或任何有用的库,以帮助这个?
是的,有json_decode
和uksort
:
$specificity = function($selector) {
/*
* @link http://www.w3.org/TR/selectors/#specificity
*
* 9. Calculating a selector's specificity
*
* A selector's specificity is calculated as follows:
*
* * count the number of ID selectors in the selector (= a)
* * count the number of class selectors, attributes selectors, and
* pseudo-classes in the selector (= b)
* * count the number of type selectors and pseudo-elements in the
* selector (= c)
* * ignore the universal selector
*
* Selectors inside the negation pseudo-class are counted like any other,
* but the negation itself does not count as a pseudo-class.
*
* Concatenating the three numbers a-b-c (in a number system with a large
* base) gives the specificity.
*/
...
return (int) $result;
}
$compare = function($a, $b) use ($specificity) {
return $specificity($a) - $specificity($b)
};
$array = json_decode('{"yours" : "json"}', true);
uksort($array, $compare);
echo json_encode((object) $array);
因为这些代码示例所示,它只是说明如何计算特异性注释,它不包含的代码。 这完全是因为我没有在手的代码,但是我已经摆在那里了规范如何做到这一点(至少对于CSS 3)。
如果你正在寻找一个CSS选择器解析器,我知道XDOM(因为我写的)。 它的问世在GitHub上: https://github.com/hakre/XDOM -这是一个100%的CSS 3兼容CSS选择器解析器。
据我所知这是大多数你会得到什么今天的现成解决方案的条款。 所有其他的CSS选择器解析器我知道是不是完全的CSS 3标准兼容,因为他们不遵循W3C的规范。 这可能是对你有好处:如果您不需要严格CSS3 compatbility,你可能会发现,满足您的需求已经有一些其他的代码块。
其实有一种通过特异性订购标准算法,我想你可能想看看那个。
CSS特异性
也可以是有用的某种试探式的,例如检查是否存在是一家领先的#或计数的空间和点的量。