更改 IE/Edge 中的 SVG 'style' 元素

Change SVGs 'style' element in IE/Edge

我有一个 SVG,其中包含一些 css。我想用 javascript 更改此 SVG 中的 style 元素,但在 IE/Edge 中你不能用 .innerHTML 更改 style 元素。相反,您需要 .styleSheet.cssText,但我无法在我的 SVG 中使用它。

这适用于非 IE 浏览器,获取和设置值:

var style  = document.getElementById('example').contentDocument.querySelector("style");
style.innerHTML = style.innerHTML.replace('foo', 'bar')

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>

如何获取和设置此 SVG 中的样式?

原来我与 .styleSheets.cssText 非常非常接近,不得不使用它略有不同。

为了让它在 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');
}

注:

值得注意的是 Firefox 和其他 return 实际编写的 innerHTML。如果您没有换行符,则结果中没有换行符:
.example1{boo:bar;}

然而,IE 和 Edge 将 return 解析结果。

.example1 {
    boo: bar;
}