如何告诉 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 SEARCH:2011年未找到答案
http://tech.groups.yahoo.com/group/svg-developers/message/56679
更新:另见 question about correctly structuring javascript, css, and svg
也许 jQuery SVG (keith-wood.name)...
最佳答案
切换实际样式表可能不是最好的主意。如果您在非常高的级别上设置 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 文档中存在外部样式表问题。
关于javascript - 动态更改外部 SVG 文件的 CSS 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7371709/