【问题标题】:Change SVGs 'style' element in IE/Edge在 IE/Edge 中更改 SVG 的“样式”元素
【发布时间】:2016-05-10 08:29:38
【问题描述】:

我有一个包含一些 css 的 SVG。我想使用 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 中获取和设置样式?

【问题讨论】:

    标签: javascript jquery svg stylesheet


    【解决方案1】:

    原来我与.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;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 1970-01-01
      • 2016-05-01
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-12
      • 1970-01-01
      相关资源
      最近更新 更多