gpt4 book ai didi

javascript - 使用javascript为css规则添加前缀

转载 作者:行者123 更新时间:2023-11-29 10:11:14 26 4
gpt4 key购买 nike

我有一个包含以下 css 的字符串,我需要用 javascript 处理

h1
{
color: red;
}

.info
{
border: 1px dotted blue;
padding: 10px;
}

#rect
{
background: pink;
}

h2,
h3,
h4
{
font-weight: bold;
}

table td:last td
{
background: gainsboro;
}

如何为每条规则添加前缀 .page 以使 css 不被破坏?

我想要这个结果

.page h1
{
color: red;
}

.page .info
{
border: 1px dotted blue;
padding: 10px;
}

...

现在,我通过查找缩进来解决它,但是代码在这种情况下失败了

h1
{
color: red;
}

然后以

结束
.page h1
{
.page color: red;
}

我也可以查找只有方括号的行,但这种情况会失败

h1 { color: red; }

我不想构建自己的 css 解析器,我发现的解析器主要处理应用于 DOM 中元素的 css,而不是带有 css 的字符串。是否有一个好的解析器或可以通过其他方式实现?

最佳答案

这是一个为所有选择器添加类名前缀的函数。此函数正确处理@规则:

var prefixCssSelectors = function(rules, className) {
var classLen = className.length,
char, nextChar, isAt, isIn;

// makes sure the className will not concatenate the selector
className += ' ';

// removes comments
rules = rules.replace( /\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g, '' );

// makes sure nextChar will not target a space
rules = rules.replace( /}(\s*)@/g, '}@' );
rules = rules.replace( /}(\s*)}/g, '}}' );

for (var i = 0; i < rules.length-2; i++) {
char = rules[i];
nextChar = rules[i+1];

if (char === '@' && nextChar !== 'f') isAt = true;
if (!isAt && char === '{') isIn = true;
if (isIn && char === '}') isIn = false;

if (
!isIn &&
nextChar !== '@' &&
nextChar !== '}' &&
(
char === '}' ||
char === ',' ||
((char === '{' || char === ';') && isAt)
)
) {
rules = rules.slice(0, i+1) + className + rules.slice(i+1);
i += classLen;
isAt = false;
}
};

// prefix the first select if it is not `@media` and if it is not yet prefixed
if (rules.indexOf(className) !== 0 && rules.indexOf('@') !== 0) rules = className+rules;

return rules;
}


// Some examples:
console.log(prefixCssSelectors('div { width: 100%; }', '.page'));

console.log(prefixCssSelectors('@charset "utf-8"; div { width: 100%; }', '.page'));

console.log(prefixCssSelectors('@media only screen { div { width: 100%; } p { size: 1.2rem; } } @media only print { p { size: 1.2rem; } } div { height: 100%; font-family: "Arial", Times; }', '.page'));

console.log(prefixCssSelectors('@font-face { font-family: "Open Sans"; src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2"); } div { width: 100%; }', '.page'));

如果您只想为 htmlbody 选择器添加类名,请添加:

rules = rules.replace(/( html| body)/g, '');

关于javascript - 使用javascript为css规则添加前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33235262/

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