动态创建的SVG呈现为HTML,但无法正确显示

时间:2018-12-24 05:45:29

标签: javascript html svg

我正在动态创建SVG元素,并将其附加到页面中的另一个元素。 该页面显示SVG元素,该元素是文件中编写的HTML DOM的一部分,但不显示通过Javascript动态创建的元素。

我检查了呈现的HTML输出,发现动态创建的SVG与HTML文件中指定的SVG之间没有区别。

var out = document.getElementById("output");
var svg = document.createElement("svg");
svg.setAttribute("width",50);
svg.setAttribute("height",50);
svg.setAttribute("style","background-color:#bada55");
svg.innerHTML = "why is this not displayed as SVG?";
out.appendChild(svg);
<div id="output">
  <svg width="50" height="50" style="background-color:beige">This one is OK</svg>
</div>

我在做什么错了?

编辑:

PS:我正在使用Chrome,并且看到输出的方式是:米色SVG正确呈现,其中没有文本。 绿色的SVG(动态创建的)看起来像是<span>,其中包含文本。

这是我所看到的图像: Here is the expected output and what I am currently seeing

这是呈现的HTML:

<div id="output">
  <svg width="50" height="50" style="background-color:beige">This one is OK</svg>
  <svg width="50" height="50" style="background-color:#bada55">why is this not displayed as SVG?</svg>
</div>

1 个答案:

答案 0 :(得分:2)

使用createElementNS,这将解决您的问题。

var out = document.getElementById("output");
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('style', 'background-color:#bada55');
svg.setAttribute('width', '50');
svg.setAttribute('height', '50');
svg.innerHTML = "why is this not displayed as SVG?";
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

out.appendChild(svg);
<div id="output">
  <svg width="50" height="50" style="background-color:beige">This one is OK</svg>
</div>

相关问题