size of createElement(“svg”) is 0,0

2020-04-14 07:52发布

I want to create an SVG with JS and set the size, but when I use createElement("svg"), the generated HTML is

<svg class="jscreated" style="width: 500px; height: 400px;"></svg>

but the svg size is shown as 0,0.

See this example:

var svg=document.createElement("svg");
document.body.appendChild(svg);
svg.setAttribute("class","jscreated");
svg.style.width="500px";
svg.style.height="400px";
<svg class="HTML_SVG" style="width:500px; height:400px;" class="HTML_SVG"></svg>

You can see that the SVG created by JS is 0,0 but the direct in HTML written one is 500x400 as it should be. What does the "==$0" in the Chrome inspector mean?

1条回答
小情绪 Triste *
2楼-- · 2020-04-14 08:18

createElement can only create HTML elements, you need createElementNS

var svg=document.createElementNS("http://www.w3.org/2000/svg", "svg");
document.body.appendChild(svg);
svg.setAttribute("class","jscreated");
svg.style.width="500px";
svg.style.height="400px";
<svg class="HTML_SVG" style="width:500px; height:400px;" class="HTML_SVG"></svg>

查看更多
登录 后发表回答