javascript + svg:在样式之外声明时获取填充

时间:2012-06-24 14:54:49

标签: javascript svg

我想在svg中替换另一个渐变,所以我需要对每个svg项进行迭代(可能递归)以获得

我查看了svg doc @ MDN https://developer.mozilla.org/fr/SVG/Element/ellipse 但它被打破(访问被拒绝,没有例子,许多断开的链接)

和MSDN的那个完全不同 http://msdn.microsoft.com/en-us/library/ie/ff972071%28v=vs.85%29.aspx

所以我搜索有关如何访问svg元素的fill属性的任何指针,但是已经定义了它。 类似于getComputedFill函数的东西

<svg 
 version="1.1"
   xmlns="http://www.w3.org/2000/svg" 
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"

 >
  <defs>
    <script>
        <![CDATA[

        function infothis(ref)
        {
        alert(ref + " " + ref.fill + " " + ref.fillOpacity); // why can't I get "url(#grad1)"  and 0.5 when clicking ellipse1
        //alert(ref.style.getPropertyValue("fill"));           // somewhat okwhy can't I get "url(#grad2)"  when clicking ellipse2

        }

        ]]>
    </script>
    <linearGradient 
    dc:title="red black filter" 
    dc:rights="CC-BY" 
    dc:description="basic filter ranging from black to red"
    id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" style="stop-color:rgb(0,0,0);stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
    </linearGradient>

    <linearGradient id="grad2" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" style="stop-color:rgb(0,0,0);stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(255,0,255);stop-opacity:1" />
    </linearGradient>

    <ellipse id="ellipse0" cx="150" cy="170" rx="85" ry="55" fill="url(#grad2)" />
  </defs>

  <ellipse id="ellipse1" cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" fill-opacity="0.5" onclick="infothis(this)" />
  <ellipse id="ellipse2" cx="100" cy="70" rx="85" ry="55" style="fill:url(#grad2)" onclick="infothis(this)" />
  <use  xlink:href="#ellipse0"/>
</svg>

1 个答案:

答案 0 :(得分:3)

这个怎么样......

alert(document.defaultView.getComputedStyle(ref, null).getPropertyValue("fill"));