开发者

Dynamically change the CSS file of an external SVG file?

How to tell to the SVG image to use another CSS file ?

  • A web page displays a SVG file.
  • A button allows to switch between classic colors to high contrast on the whole web page including the SVG image.

Attempt

w.css (white background)

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

b.css (black background)

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="开发者_JAVA技巧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: No answer found in 2011

http://tech.groups.yahoo.com/group/svg-developers/message/56679

UPDATE: See also question about correctly structuring javascript, css, and svg

Maybe jQuery SVG (keith-wood.name)...


It's probably not the best idea to switch actual stylesheets. You're probably better off if you set a CSS class on a very high level and then switching that class with Javascript. Then you can put all the CSS rules in one file and just have to use selectors like (simplified):

<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>

You know what I mean? It's like an if...else construct. If it's a descendant of someclass make it blue, otherwise make it red.

That said, I've heard that some browsers have problems with external stylesheets in SVG documents.


http://www.thesitewizard.com/javascripts/change-style-sheets.shtml happens to claim to explain how to enable/disable style sheets from javascript. Perhaps you can adapt it to SVG.

I did a quick experiment using firebug against a web page that embedded an SVG that contained a reference to an external CSS.

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

It appears to work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜