【问题标题】:How to append div tag into a SVG rect element?如何将 div 标签附加到 SVG 矩形元素中?
【发布时间】:2016-09-02 08:31:09
【问题描述】:

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

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

这是浏览器提供的我的 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>

(我正在用 JS 创建一切)。

我的问题是我在 rect 标记内创建了这个 div,但是这个 div 及其内容没有出现在矩形内的屏幕上。

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

【问题讨论】:

  • 答案很简单:你不能! SVG rect 元素不能将 div(或任何其他 HTML 元素)作为子元素。这是我为 D3 编写的文档(不是您的情况),但这完全涵盖了您的问题,请看:stackoverflow.com/documentation/d3.js/2537/… 此示例讨论错误地将 SVG 元素附加到其他 SVG 元素,同样适用于将 HTML 元素附加到SVG 元素。
  • 同上@GerardoFurtado 的评论,要在您的svg 中添加HTML 元素,您需要使用&lt;foreignObject&gt; 元素。
  • Kaiido 的提示是正确的,但请记住 IE 不支持foreignObject...
  • 你能给我一个简单的foreignObject例子的答案吗?

标签: javascript jquery html svg


【解决方案1】:

很遗憾,这是不可能的:您不能将 HTML 元素附加到 SVG 元素。

在 SVG 中使用div(或ph1li 等)的唯一方法是使用foreignObject。在您的代码中,如下所示:

<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>

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

【讨论】:

  • 有没有IE友好的解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 2017-05-10
  • 2014-01-05
  • 1970-01-01
  • 2020-01-01
  • 2016-03-26
相关资源
最近更新 更多