如何将 div 标签附加到 SVG 矩形元素中?

Ant*_*zov 2 html javascript jquery svg

我找不到这个问题的正确解决方案,所以我决定写一个新问题。

我什至不确定这是否可能,但我希望如此。

这是浏览器提供的 HTML。我从浏览器中的“元素”选项卡复制它。

<svg width="960" height="728" style="margin-left: 0px;">
<g transform="translate(0,24)" style="shape-rendering: crispEdges;">
    <g class="depth">
        <g>
            <g>
                <rect class="child" x="0" y="0" width="960" height="704" style="fill: rgb(192, 192, 192);">1.1.1.
                    <div class="jstree">
                        <div>TestContent</div>
                    </div>
                </rect>
            </g>
        </g>
    </g>
</g>
Run Code Online (Sandbox Code Playgroud)

(我用 JS 创建一切)。

我的问题是,我在 rect 标签内创建这个 div,但这个 div 及其内容不会出现在屏幕上的矩形内。

我想知道是否可以让它出现,如果是如何?

Ger*_*ado 5

不幸的是,这是不可能的:您无法将 HTML 元素附加到 SVG 元素。

在 SVG 中使用 a div(或p、等)h1的唯一方法是使用. 在你的代码中,是这样的:liforeignObject

<svg width="960" height="728" style="margin-left: 0px;">
<g transform="translate(0,24)" style="shape-rendering: crispEdges;">
    <g class="depth">
        <g>
            <g>
                <rect class="child" x="0" y="0" width="960" height="704" style="fill: rgb(192, 192, 192);">
                </rect>
                <foreignObject x="100" y="100" width="100" height="100">
		    <div xmlns="http://www.w3.org/1999/xhtml" class="jstree">
                        <div>TestContent</div>
                    </div>
	        </foreignObject>
            </g>
        </g>
    </g>
</g>
Run Code Online (Sandbox Code Playgroud)

请注意,它foreignObject位于矩形之后,而不是矩形内部(如您的代码中所示)。另请注意,这foreignObject在 IE 中不起作用:https://developer.mozilla.org/en/docs/Web/SVG/Element/foreignObject