创建元素( "svg" ) 的大小为 0,0



我想用JS创建一个SVG并设置大小,但是当我使用createElement("svg")时,生成的HTML是

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

,但svg的大小显示为0,0

请看下面的例子:

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>

你可以看到由JS创建的SVG是0,0,但直接在HTML中编写的SVG应该是500x400。Chrome检查器中的"==$0"是什么意思?

createElement只能创建HTML元素,您需要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>

最新更新