我可以将 HTML 嵌入到 HTML5 SVG 片段中吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6538918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I embed HTML into an HTML5 SVG fragment?
提问by Serge Wautier
HTML5 supports the <svg>
tag, allowing to embed SVG into HTML.
HTML5 支持<svg>
标签,允许将 SVG 嵌入到 HTML 中。
Digging a little deeper, can I nest some HTML inside my <svg>
fragment? For example, I'd like to put a CSS'ed <table>
in some part of my SVG graphics.
深入一点,我可以在<svg>
片段中嵌套一些 HTML吗?例如,我想<table>
在我的 SVG 图形的某些部分添加CSS 。
I made a small test and Chrome12 didn't like the HTML <p>
inside the <svg>
.
Is there some technique to make it work (such as maybe an html container tag?)?
我做了一个小测试和Chrome12没有像HTML<p>
里面<svg>
。是否有一些技术可以使其工作(例如可能是 html 容器标签?)?
采纳答案by Erik Dahlstr?m
Yes, with the <foreignObject>
element, see this questionfor some examples.
是的,对于<foreignObject>
元素,请参阅此问题以获取一些示例。
Alternatively, if you have an html5 document you can also use CSS positioning and z-index to make parts of html visible where you want laid out on top of the svg. If you do it like that you don't need to nest the html inside the svg fragment. This will give you the most consistent behaviour across browsers in my experience.
或者,如果您有一个 html5 文档,您还可以使用 CSS 定位和 z-index 使部分 html 可见,您希望在 svg 顶部布局。如果您这样做,则不需要将 html 嵌套在 svg 片段中。根据我的经验,这将为您提供跨浏览器最一致的行为。
回答by atluriajith
Foreign Objects are not supported on Internet explorer. Please check ForeignObject
Internet Explorer 不支持异物。请检查ForeignObject
回答by mathheadinclouds
Copied from bl.ocks.org(thank you, Janu Verma)
复制自bl.ocks.org(谢谢,Janu Verma)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML inside SVG</title>
<style type="text/css"></style></head>
<body>
<div>I'm a div inside the HTML</div>
<svg width="500" height="300" style="border:1px red solid" xmlns="http://www.w3.org/2000/svg">
<foreignobject class="node" x="46" y="22" width="100" height="100">
<div style="border:1px green solid">I'm a div inside a SVG.</div>
</foreignobject>
<circle cx="100" cy="160" r="50" fill="blue"></circle>
</svg>
<div>Interesting! But you a Foreign Object.</div>
</body>
</html>
UPDATE
更新
Note that there is a 'camel error' in the above - it's supposed to be foreignObject
(capital O), not foreignobject
. It doesn't matter if the misspelling is in 'straight' HTML/SVG. But if you use JavaScript (.createElementNS
), then it won't work without proper camel case (April 2020)
请注意,上面有一个“骆驼错误”——它应该是foreignObject
(大写 O),而不是foreignobject
. 拼写错误是否在“直”HTML/SVG 中并不重要。但是,如果您使用 JavaScript ( .createElementNS
),那么如果没有适当的驼峰式大小写,它将无法工作(2020 年 4 月)