如何在SVG中获得动态javascript引用

How to get a working dynamic javascript reference in an SVG

本文关键字:动态 javascript 引用 SVG      更新时间:2023-09-26

我想做的是从HTML中的Javascript代码动态地设置嵌入SVG文档中的Javascript脚本引用。

我认为这就像动态地将节点附加到嵌入的SVG文档中的适当位置一样简单。

我发现节点实际上是在运行时添加的(可以用Firefox Inspect Element检查这一点),但是引用中包含的Javascript代码在需要时没有执行。

有人知道这个吗?还需要做什么才能使SVG能够调用Javascript代码中的函数吗?

下面是一个简化的场景:

test.html(嵌入SVG)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
    function ActivateScript() {
      var svgdoc = document.getElementById("svg");
      var newref = svgdoc.contentDocument.createElement('script');
      newref.setAttribute("type", "text/javascript");
      newref.setAttribute("xlink:href", "script.js");
      svgdoc.contentDocument.documentElement.appendChild(newref);
    }
</script>
</head>
<body>
<input type="button" value="Activate script" onclick="ActivateScript()" />
<object id="svg" type="image/svg+xml" data="embed.svg"/>
</body>
</html>

embed.svg

<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="12cm" height="12cm" xmlns:xlink="http://www.w3.org/1999/xlink">
<g style="fill-opacity:1; stroke:black; stroke-width:0.1cm;">
<circle cx="6cm" cy="2cm" r="100" style="fill:red;" transform="translate(0,50)" onclick="MyFunction()"/>
</g>
</svg>

最后是外部Javascript,我试图动态分配(script.js)

function MyFunction() {
alert("I can execute script!");
}

SVG元素必须在SVG命名空间http://www.w3.org/2000/svg中创建所以不是createElement而是使用createElementNS类似的xlink属性也必须放在xlink命名空间中所以需要

  var newref = svgdoc.contentDocument.createElementNS('http://www.w3.org/2000/svg', 'script');
  newref.setAttribute("type", "text/javascript");
  newref.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "script.js");