javascript无法在embed svg文件中使用

时间:2016-04-21 19:01:20

标签: javascript svg

我刚开始学习SVG。从Manipulating SVG Documents Using ECMAScript (Javascript) and the DOM得到了这个示例代码。我稍微改了一下:

<!DOCTYPE html>
<html>
<body>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">
  <script type="text/ecmascript">
  <![CDATA[
    function changeRectColor(evt) {
      var red = Math.round(Math.random() * 255);
      evt.target.setAttributeNS(null,"fill","rgb("+ red +","+ red+","+red+")");
    }
  ]]>
  </script>
  <g id="firstGroup">
    <rect id="myBlueRect" width="100" height="50" x="40" y="20" fill="blue" onclick="changeRectColor(evt)"/>
    <text x="40" y="100">Click on rectangle to change it's color.</text>
  </g>
</svg>
</body>
</html>

它运作得很好。我转到分离的SVG文件,然后js代码停止工作:

<!DOCTYPE html>
<html>
<body>
<object type="image/svg+xml" data="exampl3a.svg" />   
  <script type="text/ecmascript">
  <![CDATA[
    function changeRectColor(evt) {
      var red = Math.round(Math.random() * 255);
      evt.target.setAttributeNS(null,"fill","rgb("+ red +","+ red+","+red+")");
    }
  ]]>
  </script>
</body>
</html>

SVG文件:exampl3a.svg

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">
  <g id="firstGroup">
    <rect id="myBlueRect" width="100" height="50" x="40" y="20" fill="blue" onclick="changeRectColor(evt)"/>
    <text x="40" y="100">Click on rectangle to change it's color.</text>
  </g>
</svg>

我该怎么办?

由于 韦斯

1 个答案:

答案 0 :(得分:2)

如果您将svg放入另一个文件中,那么它将存在于另一个文档中,您需要使用getSVGDocument绑定到该文档。是的,这仍然无法在Chrome中用于本地文件(仅适用于网站,或者除非Chrome使用相应的命令行切换运行)。

SVG:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">
  <g id="firstGroup">
    <rect id="myBlueRect" width="100" height="50" x="40" y="20" fill="blue" />
    <text x="40" y="100">Click on rectangle to change it's color.</text>
  </g>
</svg>

HTML

<!DOCTYPE html>
<html>
<body>
<object id='mySvg' type="image/svg+xml" data="example3a.svg" />
<script type="text/ecmascript">
    function changeRectColor(evt) {
        var red = Math.round(Math.random() * 255);
        evt.target.setAttributeNS(null,"fill","rgb("+ red +","+ red+","+red+")");
    }

    var obj = document.getElementById('mySvg');
    obj.addEventListener('load', function() {
        var svgDoc= obj.getSVGDocument();
        var elem = svgDoc.getElementById("myBlueRect");
        elem.addEventListener('click', changeRectColor);
    });
</script>
</body>
</html>
相关问题