更改SVG'style'元素

Change SVGs 'style' element in IE/Edge

本文关键字:元素 style SVG 更改      更新时间:2023-09-26

我有一个SVG,它包含一些css。我想用javascript更改这个SVG中的style元素,但在IE/Edge中你可以;t用CCD_ 3改变CCD_。相反,您需要.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和其他浏览器在编写时会返回实际的innerHTML。如果没有换行符,则结果中没有换行符:
.example1{boo:bar;}

然而,IE和Edge将返回解析后的结果。

.example1 {
    boo: bar;
}