在运行时向我的文档添加更多svg元素

use*_*114 6 javascript svg

我有一个html文件,我正在动态添加am元素,然后是一个矩形.适用于不同的浏览器(忽略IE).当我尝试使用相同的方法动态创建元素时,它在Chrome或Safari中无效,仅在Opera中有效.我的语法错了,或者webkit可能不支持在运行时添加元素?(如果我将其声明为标签,则相同的元素可以正常工作).也许我不应该对这些类型的节点使用appendChild()?这就是我所拥有的,您应该能够将其转储到html文件中并运行它.如果有人知道如果有办法解决这个问题,那就太好了:

<html>
<head>
  <script>

    window.onload = function() {
        var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
        svg.setAttribute('version', '1.1');
        svg.setAttribute('width', '800px');
        svg.setAttribute('height', '400px');
        document.body.appendChild(svg);

        var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
        rect.setAttribute("id", "myrect"); 
        rect.setAttribute("fill","red");
        rect.setAttribute("stroke","black");
        rect.setAttribute("stroke-width","5");
        rect.setAttribute("x", "100");
        rect.setAttribute("y", "100");
        rect.setAttribute("width", "100");
        rect.setAttribute("height", "50");
        svg.appendChild(rect);

        var anim = document.createElementNS('http://www.w3.org/2000/svg','animate');
        anim.setAttribute("attributeName", "width");
        anim.setAttribute("from", "100");
        anim.setAttribute("to", "400");
        anim.setAttribute("dur", "10s");
        anim.setAttribute("begin", "0s");
        anim.setAttribute("fill", "freeze");
        rect.appendChild(anim);
    }

</script>
</head>

<body>
</body>
Run Code Online (Sandbox Code Playgroud)

Kyl*_*utt 4

当使用setAttributeNS(null, ...)document.createElementNS().

来自xmlgraphics.apache.org/batik/faq.html

然而,重要的是要知道某些实现在 setAttribute(x, y) 和 setAttributeNS(null, x, y) 之间存在差异,因此使用 setAttributeNS 是一个很好的做法,它是在属性中设置属性的唯一有保证的可互操作方式。命名空间感知 DOM 实现。