动态更改外部SVG文件的CSS文件?

时间:2011-09-10 12:36:50

标签: javascript css xml svg stylesheet

如何告诉SVG图像使用其他CSS文件?

  • 网页显示SVG文件。
  • 按钮允许在整个网页上切换经典颜色和高对比度,包括SVG图像。

尝试

w.css (白色背景)

svg { background-color:white; }
path{ fill:none; stroke:black; stroke-width:8px; }

b.css (黑色背景)

svg { background-color:black; }
path{ fill:none; stroke:white; stroke-width:10px; }

image.svg

<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="w.css" title="classic" ?>
<?xml-stylesheet type="text/css" href="b.css" title="contrast" alternate="yes" ?>
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
   <path d="M150,100 H50 V300 H150 M250,300 H300" />
</svg>

example.html

<html>
<body>

<embed id="svg_image" src="image.svg" type="image/svg+xml" /> 

<script type="text/javascript">
var embed = document.getElementById("svg_image");
function change_css(file){
    var svgdoc = embed.getSVGDocument();
    var b = svgdoc.childNodes;
    for (var i=0; i<b.length; i++){
        var itm = b.item(i);
        itm.Data = "href='"+ file +"' type='text/css'" ;
    }
}
</script>

<input name="c" type="radio" onclick="change_css('b.css');">High contrast<br>
<input name="c" type="radio" onclick="change_css('w.css');" checked="yes">Classic

</body>
</html>

WEB搜索: 2011年没有找到答案 http://tech.groups.yahoo.com/group/svg-developers/message/56679

更新另请参阅question about correctly structuring javascript, css, and svg
也许是jQuery SVG(keith-wood.name)......

2 个答案:

答案 0 :(得分:2)

切换实际样式表可能不是最佳选择。如果你在一个非常高的级别设置一个CSS类,然后用Javascript切换该类,你可能会更好。然后,您可以将所有CSS规则放在一个文件中,只需使用选择器,如(简化):

<svg xmlns="http://www.w3.org/2000/svg" class="someclass">
    <style>
        .someclass .mypath { stroke: blue; }
        .someotherclass .mypath { stroke: red; }
    </style>
    <path d="M150,100 H50 V300 H150 M250,300 H300" class="mypath" />
</svg>

你知道我的意思吗?它就像一个if ... else结构。如果它是someclass的后代,则将其设为蓝色,否则将其设为红色。

那就是说,我听说有些浏览器在SVG文档中有外部样式表的问题。

答案 1 :(得分:2)

http://www.thesitewizard.com/javascripts/change-style-sheets.shtml碰巧声称解释如何从javascript启用/禁用样式表。也许您可以将其改编为SVG。

我使用firebug对嵌入了包含对外部CSS的引用的SVG的网页进行了快速实验。

o=document.getElementsByTagName("object")
svg = o[0].getSVGDocument()
svg.styleSheets[0].disabled = true

似乎有效。