我有一个包含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获取字符串
发布于 2018-08-14 06:47:01
OP询问是否可以这样做,并指定(在我阅读时)删除重复的规则。简单化的方法:
按规则拆分输出字符串结束空格并将delimiter
中
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;
}
https://stackoverflow.com/questions/51831278
复制相似问题