[英]Change SVGs 'style' element in IE/Edge
I have a SVG which contains a bit of css. 我有一个包含一些CSS的SVG。 I want to change the
style
element in this SVG, with javascript, but in IE/Edge you can;t change the style
element with .innerHTML
. 我想使用javascript更改此SVG中的
style
元素,但是在IE / Edge中,您不能使用.innerHTML
更改style
元素。 Instead, you need .styleSheet.cssText
, but I cant get it to work in my SVG. 相反,您需要
.styleSheet.cssText
,但是我无法在SVG中使用它。
This works in non-IE browsers, to get and set the value: 这适用于非IE浏览器,用于获取和设置值:
var style = document.getElementById('example').contentDocument.querySelector("style");
style.innerHTML = style.innerHTML.replace('foo', 'bar')
The SVG (simplified): SVG(简体):
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 540 494.08">
<defs>
<style id="SvgStyleSheet">
.someClass{}
</style>
<!-- Some more definitions -->
</defs>
<!-- SVG elements here -->
</svg>
How do I get and set the style in this SVG? 如何在此SVG中获取和设置样式?
Turns out I was very very close with .styleSheets.cssText
, had to use it slightly different. 原来,我与
.styleSheets.cssText
非常接近,不得不使用稍有不同的方式。
In order to keep it working in IE/Edge, Firefox, Android, Chrome and iPhone's browser, I had to implement both. 为了使其能够在IE / Edge,Firefox,Android,Chrome和iPhone的浏览器中正常工作,我必须同时实现这两者。
var svgDOC = document.getElementById('idOfSVG').contentDocument;
style = svgDOC.styleSheets[0];
// IE/Edge
if( typeof style.cssText !== "undefined" ){
style.cssText = style.cssText.replace('foo', 'bar');
}
// Non IE/Edge:
else{
var style = svgDOC.querySelector("style");
style.innerHTML = style.innerHTML.replace('foo', 'bar');
}
Note: 注意:
It's worth noting that Firefox and other return the actual innerHTML as it is written. 值得注意的是,Firefox和其他浏览器在编写时会返回实际的innerHTML。 If you have no newlines, no newline are in the result:
如果没有换行符,则结果中没有换行符:
.example1{boo:bar;}
IE and Edge however will return a parsed result. IE和Edge但是将返回解析的结果。
.example1 {
boo: bar;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.