使用javascript在svg中添加动态异物

Pra*_*jal 12 javascript svg

当我运行此代码时,它向我显示一个空白屏幕但是当我使用chrome中的开发人员工具更新代码时,它会显示数据.请帮助解释为什么它显示我使用chrome的开发人员工具更新代码的时候,是因为浏览器再次运行DOM,如果是,那么为什么不在第一次显示它时.这是否由于foreignObject而发生.

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
    <svg id="t">
    <g>
        <text x="10" y="10">hello</text>
    </g>
    </svg>
        <script>
            var s = document.getElementById('t');
            var g = s.childNodes[1];
            console.log(g.childNodes[1].remove());
            var foreign = document.createElementNS('http://www.w3.org/2000/svg',"foreignObject");

            foreign.setAttribute('width', 500);
            foreign.setAttribute('height', 150);
            var txt = document.createElementNS('http://www.w3.org/2000/svg', 'text');
            txt.setAttribute('x', '10');
            txt.setAttribute('y', '10');
            var t = document.createTextNode("This is a paragraph.");
            txt.appendChild(t);
            foreign.appendChild(txt);
            g.appendChild(foreign);

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

小智 10

@JabranSaeed if you want to use foroeignObject,beter to follow this method 

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
    <svg id="t">
    <g>

    </g>
    </svg>
<script>
  var s = document.getElementById('t');
        var g = s.childNodes[1];

        var foreign = document.createElementNS

('http://www.w3.org/2000/svg',"foreignObject");

        foreign.setAttribute('width', 500);
        foreign.setAttribute('height',500);
        var iDivele = document.createElement('div');
        var ob = document.createTextNode("xxxx");
        iDiv.appendChild(ov);
        foreign.appendChild(iDivele);

        g.appendChild(foreign);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • `varforeign = document.createElementNS('http://www.w3.org/2000/svg',"foreignObject");` 我没有意识到,但是这里的命名空间对于foreignObject的渲染非常重要。更改我的代码以使用正确的命名空间解决了我真正令人沮丧的问题 (2认同)

Pra*_*jal 2

@JabranSaeed if you want to use foroeignObject to insert non svg element then:

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
    <svg id="t">
    <g>

    </g>
    </svg>
<script>
  var s = document.getElementById('t');
        var g = s.childNodes[1];

        var foreign = document.createElementNS

('http://www.w3.org/2000/svg',"foreignObject");

        foreign.setAttribute('width', 500);
        foreign.setAttribute('height',500);
        var iDiv = document.createElement('div');
        var t = document.createTextNode("This is a paragraph.");
        iDiv.appendChild(t);
        foreign.appendChild(iDiv);

        g.appendChild(foreign);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)