浏览器不会呈现动态创建的 SVG 元素 [英] Dynamically created SVG elements are not rendered by the browser
问题描述
我试图在我的 HTML 中使用 SVG 标记来呈现一些图形.这个问题非常棘手,因为我刚刚意识到问题出在以编程方式生成 SVG 时.
I am trying to use SVG markup in my HTML in order to render some graphics. The problem was very tricky because I just realized that the issue is when generating the SVG programmatically.
我想要在我的页面中结束的是这段代码:
What I want to end up in my page is this fragment of code:
<svg>
<circle cx="20" cy="20" r="15"></circle>
</svg>
如果您将其粘贴到页面中,则一切正常,并且会呈现一个黑色圆圈!
If you take this and paste it inside a page, all is fine and the a black circle is rendered!
但我想用 Javascript 创建这个内容,所以我有这个:
But I want to create this content using Javascript, so I have this:
var container = document.createElement("div");
var svg = document.createElement("svg");
var circle = document.createElement("circle");
circle.setAttribute("cx", "20");
circle.setAttribute("cy", "20");
circle.setAttribute("r", "15");
svg.appendChild(circle);
container.appendChild(svg);
document.body.appendChild(container);
好吧,尝试在 fiddle 或浏览器中执行此操作,您会看到它不会被呈现.当您检查 HTML 时,您会看到 circle
没有占用任何空间.
Well, try to execute this in fiddle or in your browser and you'll see it will not be rendered. When you inspect the HTML, you see that the circle
is not taking any space.
有什么问题?
推荐答案
你必须使用 "document.createElementNS("http://www.w3.org/2000/svg", "svg");"
创建 svg 元素
you have to use "document.createElementNS("http://www.w3.org/2000/svg", "svg");"
to create svg elements
var container = document.createElement("div");
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "20");
circle.setAttribute("cy", "20");
circle.setAttribute("r", "15");
svg.appendChild(circle);
container.appendChild(svg);
document.body.appendChild(container);
这篇关于浏览器不会呈现动态创建的 SVG 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!