<分区>
我有一个包含 CSS 的字符串,尽管其中很多都有重复的样式。
.button:hover {background: #fff} p.test {font-size: 11px} .button:hover {background: #fff} .button:hover {background: #fff}...
我怎样才能从那个字符串中删除重复的 CSS 样式,这样上面的例子就变成了:
.button:hover {background: #fff} p.test {font-size: 11px}
所有样式都位于 <style></style>
中标记,我通过使用 $("style").html()
使用 jQuery 获取字符串
最佳答案
OP 询问是否可以完成并指定(如我所读)删除重复规则。一种简单的方法:
var style = ".button:hover {background: #fff} p.test {font-size: 11px} .button:hover {background: #fff} .button:hover {background: #fff} #one .button {color: #000} #two .button {color: #000}";
var uniqueRules = style
.split('}')
.map(function(rule) {
return rule ? rule.trim() + '}' : '';
})
.filter(function(rule, index, self) {
return self.indexOf(rule) === index;
})
.join(' ');
console.log(uniqueRules);
使用 CSSOM(CSS 对象模型)
我添加这个是因为有人错误地声称“浏览器会自动为您完成(CSSOM 是您当前应用的所有 CSS 的优化结果)”。注意重复的样式 .as-console-wrapper { position: fixed; }
。那里的优化非常好。也许批评者想发布一个答案来解释他怎么可能弄错了?
var allCSS =
[].slice.call(document.styleSheets)
.reduce(function (prev, styleSheet) {
if (styleSheet.cssRules) {
return prev +
[].slice.call(styleSheet.cssRules)
.reduce(function (prev, cssRule) {
return prev + cssRule.cssText;
}, '');
} else {
return prev;
}
}, '');
console.log(allCSS);
.as-console-wrapper {position: fixed;}
.as-console-wrapper {position: fixed;}
不过,CSSOM 确实为我们做了一些事情。它将规范化(不要与优化混淆)允许我们找到完全重复的规则,而不必担心空格、丢失分号等问题。
var allCSS =
[].slice.call(document.styleSheets)
.reduce(function (prev, styleSheet) {
if (styleSheet.cssRules) {
return prev +
[].slice.call(styleSheet.cssRules)
.reduce(function (prev, cssRule) {
return prev + cssRule.cssText;
}, '');
} else {
return prev;
}
}, '');
var uniqueRules = allCSS
.split('}')
.map(function(rule) {
return rule ? rule.trim() + '}' : '';
})
.filter(function(rule, index, self) {
return self.indexOf(rule) === index;
})
.join(' ');
console.log(uniqueRules);
.as-console-wrapper {position: fixed;}
.as-console-wrapper {position: fixed}
.as-console-wrapper {position:fixed;}
.as-console-wrapper {
position: fixed;
}
.as-console-wrapper
{
position: fixed;
}
关于javascript - 如何使用 JavaScript 从字符串中删除重复的 CSS 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51831278/