【发布时间】:2017-07-27 09:22:42
【问题描述】:
是否可以使用 JS 检索浏览器默认值的 CSS 属性,忽略任何内联/导入的样式?
一些上下文:我正在使用 JS 内联特定 SVG 元素及其子元素的所有样式(这允许我使用 canvg 将其转换为 PNG)。目前,我的输出因每种可用样式而变得非常臃肿,我希望能够从包含在内的样式数组中丢弃任何使用浏览器默认值的属性。
正在发生的事情的演示:
$.extend($.fn, {
makeCssInline: function() {
this.each(function(idx, el) {
var style = el.style;
var properties = [];
for (var property in style) {
if ($(this).css(property)) {
// TODO: Only in-line this style if it's not browser default
properties.push(property + ':' + $(this).css(property));
}
}
this.style.cssText = properties.join(';');
$(this).children().makeCssInline();
});
}
});
$(document).ready(function() {
$("#before").text($("svg")[0].outerHTML.length);
$("svg").makeCssInline();
$("#after").text($("svg")[0].outerHTML.length);
});
svg circle {
fill: #080;
}
svg text {
fill: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg version="1.1" baseProfile="full" width="300" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="150" cy="50" r="50" />
<text x="150" y="65" font-size="40" text-anchor="middle">SVG</text>
</svg>
<p>Total characters before in-lining styles: <span id="before"></span></p>
<p>Total characters after in-lining styles: <span id="after"></span></p>
如您所见,即使对于简单的 SVG,此过程也会添加大量不必要的数据。
【问题讨论】:
-
I would like to be able to discard any properties which are using the browser default values.这不是 CSS 的工作原理。无论您是否设置它,所有属性总是在每个元素上设置。您不能删除 CSS 属性,只能将其设置回默认值。这就是为什么使用css()是一个坏主意的部分原因。使用类来设置元素的样式,然后您可以根据需要打开/关闭该类。 -
@RoryMcCrossan 对不起,措辞不当。我的意思是我希望能够从我的数组中丢弃默认样式,这些样式将被内联附加。
-
嗯,好的。即使在这种情况下,您也需要为自己做很多额外的工作。我强烈建议改用类。
-
我希望我可以,不幸的是 canvg(我用来从 svg 到 png 的库)需要内联样式才能正确生成输出。而且似乎没有任何其他图书馆可以满足这一要求。
标签: javascript jquery css svg canvg