gpt4 book ai didi

php - 根据选择器特异性排序 CSS

转载 作者:可可西里 更新时间:2023-11-01 13:26:50 25 4
gpt4 key购买 nike

我已经将给定的 CSS 文件/字符串解析为 JSON 对象,如下所示:

{
"#header": {
"color": "#000000"
},
"#header h1": {
"color": "#000"
},
"h1": {
"color": "#4fb6e5"
}
}

我现在要做的是根据特异性对它们重新排序。在这种情况下,#header h1 应该在 JSON 对象中的 h1 之后,因为这是它们在浏览器中的应用方式。

我该怎么做?是否有任何现有的图书馆?或者任何有用的库来帮助解决这个问题?

我可以同时使用 Javascript/jQuery 或 PHP 来执行此操作。我正在寻找实现建议,希望这已经完成了!

最佳答案

简短的回答:

Are there any existing libraries for this?

不,据我所知,没有人为您做到这一“开箱即用”。

Or any useful libraries to help with this?

是的,有json_decodeuksort :

$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 兼容性,您可能会找到一些已经满足您需求的其他代码块。

关于php - 根据选择器特异性排序 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10636340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com