使用jquery动态地将foreignObject插入到svg中

dur*_*lka 10 jquery svg

鉴于此html + svg

<div id="svg" style="width: 300px; height: 300px">
    <svg xmlns="http://www.w3.org/2000/svg"  width="300" height="300">
        <svg x='10' y='10' id='group'>
           <rect id="rect" x='0' y='0' width='100' height='100'  fill='#f0f0f0'/>
        </svg>
        <svg x='100' y='100' id='group2'>
           <rect id="rect2" x='0' y='0' width='100' height='100' fill='#f00000'/>
           <foreignobject x='0' y='0' width='100' height='100' >
                <body>
                    <div>manual</div>
                </body>
           </foreignobject>
        </svg>
    </svg>
</div>
Run Code Online (Sandbox Code Playgroud)

我想将一个foreignObject插入#group(最好使用jquery,因为它使操作更简单).我试过了(代码从头部粗略)

$("#group").append("<foreignobject x='0' y='0' width='100' height='100'><body><div>auto</div></body></foreignobject>") 
Run Code Online (Sandbox Code Playgroud)

无济于事,因为"身体"被剥夺了.我已经尝试了几种创造身体元素的异乎寻常的方法,并且我能做到最好 - 萤火虫不再灰化插入的foreignObject元素,但它仍然不可见.

所以要么我没有看到明显的东西,要么有一种奇怪的方式来做到这一点.

想法?

最终解决方案更新 这是我提出的最短内容

var foreignObject = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject' );
var body = document.createElement( 'body' ); // you cannot create bodies with .apend("<body />") for some reason
$(foreignObject).attr("x", 0).attr("y", 0).attr("width", 100).attr("height", 100).append(body);
$(body).append("<div>real auto</div>");
$("#group").append(foreignObject);
Run Code Online (Sandbox Code Playgroud)

Rob*_*son 6

SVG区分大小写,您想要的元素名称称为foreignObject.要使用dom创建它,您可以调用它

document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject')
Run Code Online (Sandbox Code Playgroud)