JavaScript在嵌入SVG文件中不起作用

javascript not working in embed svg file

本文关键字:文件 不起作用 SVG JavaScript      更新时间:2023-09-26

我刚开始学习SVG。 从使用 ECMAScript (Javascript) 和 DOM 操作 SVG 文档 (Manipulationpulating SVG Documents ) 中获取了此示例代码。我稍微改变了一下:

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

我该怎么办?

谢谢韦斯

如果您将 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>
这是我

的经验:它getSVGDocument在服务器上工作(Github工作),但不适用于本地文件。如果你有一台较旧的计算机(Windows XP),它也可以处理。