我在使用嵌入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
答案 0 :(得分:0)
您可能遇到的一个问题是,只要加载页面就运行脚本,而不是等待加载所有元素。
所以基本上是document.getElementById('pozadi');当你运行它时可能为null,并且由于你有一个外部请求(http://www.w3.org/2000/svg),很有可能发生这种情况。
尝试添加onload侦听器,使用当前脚本调用函数。如果您有jQuery,那么您正在寻找http://api.jquery.com/ready/。如果不是......手动制作。
答案 1 :(得分: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 to prove it。