2

我在嵌入 html 的 svg 图像中使用 javascript 构建 svg 元素时遇到问题。我创建了两个应该完全相同的文件,但其中一个是用 js 构建的。

SVG.html

<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="utf-8" />
  <title>Pozadí</title>
 </head>
 <body>
  <svg
    id="pozadi"
    xmlns="http://www.w3.org/2000/svg"
    version="1.1"
    height="200"
    width="200"
   >
   <path
     d="M 0,0 L 150,150 L 100,150 L 150,150 L 150,100"
     style="stroke: #000; stroke-width: 2px; stroke-linecap: round; fill: none;"
    >
    <animate
      from="M 0,0 L 150,0 L 115,35 L 150,0 L 115,-35"
      to="M 0,0 L 150,150 L 100,150 L 150,150 L 150,100"
      dur="10s"
      begin="5s"
      attributeType="XML"
      attributeName="d"
     >
    </animate>
   </path>
  </svg>
 </body>
</html>


JS.html

<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="utf-8" />
  <title>Pozadí</title>
 </head>
 <body>
  <svg
    id="pozadi"
    xmlns="http://www.w3.org/2000/svg"
    version="1.1"
    height="200"
    width="200"
   >
  </svg>
  <script>
   var svg  = document.getElementById('pozadi');
   var path = document.createElementNS('http://www.w3.org/2000/svg/','path'); //I have tried createElement(string) too
   path.setAttribute('style',"stroke: #000; stroke-width: 2px; stroke-linecap: round; fill: none;");
   path.setAttribute('d',"M 0,0 L 150,150 L 100,150 L 150,150 L 150,100");
   var anim = document.createElementNS('http://www.w3.org/2000/svg/','animate');
   anim.setAttribute('from','M 0,0 L 150,0 L 115,35 L 150,0 L 115,-35');
   anim.setAttribute('to','M 0,0 L 150,150 L 100,150 L 150,150 L 150,100');
   anim.setAttribute('dur','10s');
   anim.setAttribute('begin','5s');
   anim.setAttribute('attributeType','XML');
   anim.setAttribute('attributeName','d');
   path.appendChild(anim);
   svg .appendChild(path);
  </script>
 </body>
</html>

第二个文件 JS.html 是纯白色的。
我想问,怎么改正?谢谢,m93a

4

2 回答 2

0

您可能遇到的问题之一是您在加载页面后立即运行脚本,而不是等待所有元素加载。

所以基本上 document.getElementById('pozadi'); 运行它时可能为空,并且由于您有外部请求(http://www.w3.org/2000/svg),因此很有可能发生这种情况。

尝试使用当前脚本添加一个调用函数的 onload 侦听器。如果你有 jQuery,这就是你正在寻找的http://api.jquery.com/ready/。如果没有...手动制作。

于 2013-04-09T13:52:32.847 回答
0
var path = document.createElementNS('http://www.w3.org/2000/svg/','path');

是错的。你要

var path = document.createElementNS('http://www.w3.org/2000/svg','path');

请注意缺少尾随 / 字符。同样的问题

var anim = document.createElementNS('http://www.w3.org/2000/svg/','animate');

如果您修复这两行,您应该会看到箭头(我在 Firefox 中这样做),这是一个jsfiddle 来证明它

于 2013-04-09T13:58:25.613 回答