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

oli*_*bre 5 javascript css xml svg stylesheet

如何告诉 SVG 图像使用另一个 CSS 文件?

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

试图

w.css (白色背景)

svg { background-color:white; }
path{ fill:none; stroke:black; stroke-width:8px; }
Run Code Online (Sandbox Code Playgroud)

b.css (黑色背景)

svg { background-color:black; }
path{ fill:none; stroke:white; stroke-width:10px; }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

网络搜索: 2011 年未找到答案
http://tech.groups.yahoo.com/group/svg-developers/message/56679

更新:另请参阅有关正确构建 javascript、css 和 svg 的问题,
也许 jQuery SVG (keith-wood.name)...

Dan*_*Man 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>
Run Code Online (Sandbox Code Playgroud)

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

也就是说,我听说某些浏览器在处理 SVG 文档中的外部样式表时存在问题。