2013-04-12 58 views
6

我创建了一个我打算用作CSS背景图像的SVG文件。我希望能够使用查询字符串参数更改填充颜色在SVG,像这样:了解SVG查询字符串参数

#rect  { background-image: url('rect.svg'); } 
#rect.red { background-image: url('rect.svg?color=red'); } 

据我了解,使用的SVG脚本标签,我能够得到color参数并更新填充颜色。下面是一个例子SVG:

<!DOCTYPE svg PUBLIC "-//W3C//DDTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> 
<svg version="1.1" xmlns="http://www.w3.org/2000/svg"> 
    <rect width="100%" height="100%" /> 

    <script> 
    <![CDATA[ 
     var params = { }; 
     location.href.split('?')[1].split('&').forEach(
      function(i) 
      { 
       params[ i.split('=')[0] ] = i.split('=')[1]; 
      } 
     ); 

     if(params.color) 
     { 
      var rect = document.getElementsByTagName("rect")[0]; 
      rect.setAttribute("fill", params.color); 
     } 
    ]]> 
    </script> 
</svg> 

将文件直接或使用对象的标签似乎工作,但对于CSS背景图像或的img标签,颜色参数被忽略。

我不完全确定这里发生了什么,我希望有一个解释或替代解决方案,我试图完成(最好不诉诸于服务器端处理)。

这里是一个的jsfiddle显示不同的渲染方法:http://jsfiddle.net/ehb7S/

+4

当SVG被用作CSS背景图像或图像标签时,javascript被禁用。 –

+0

啊,这解释了为什么它不起作用。如果有任何其他聪明的解决方案通过CSS将参数传递给SVG,我将保持开放状态,但看起来我可能不太会运气。 – Quantastical

+0

为什么不在svg之外使用一些js? – mihai

回答

1

我最终创建了一个服务器端解决方案,允许我将颜色填充注入到SVG文件中。从本质上讲,我重定向所有SVG请求,做对他们下面的PHP文件:

$filename = $_SERVER['SCRIPT_FILENAME']; 

$svg = simplexml_load_file($filename); 
if(isset($_GET['color'])) 
{ 
    $svg->path->addAttribute('fill', '#' . $_GET['color']); 
} 

header("Content-type: image/svg+xml"); 
echo $svg->asXML(); 

显然,还有更多一点它比,有什么用处理缓存和这样的,但是这是肉N-土豆。可能要检查fill属性是否已经存在。

4

您可以使用内联SVG是隐藏的,改变这种状况,动态编码它作为你投入background-image属性数据URL。你的HTML可能看起来像:

<div id="backgroundContainer" style="display:none"> 
    <svg width="100px" height="100px" id="backgroundSvg" xmlns="http://www.w3.org/2000/svg"> 
     <circle cx="50" cy="50" r="50" fill="green"/> 
    </svg> 
</div> 

<div id="divWithBackground" onclick="changeBackground(event)"> 
    Click to change background SVG to random color 
</div> 

和你的JavaScript像

changeBackground = function(event) { 
    var backgroundSvg = document.getElementById("backgroundSvg"); 
    var backgroundContainer = document.getElementById("backgroundContainer"); 
    backgroundSvg.getElementsByTagName("circle")[0].setAttribute(
    "fill", 
    ["red","green","blue","black"][Math.floor(4*Math.random())] 
); 
    event.target.setAttribute(
    "style", 
    "background-image:url(data:image/svg+xml," 
    + encodeURI(backgroundContainer.innerHTML) 
    + ")" 
); 
} 

proof of concept on jsFiddle