问题
svg size isn't working with javascript no mater what I do. I tried every thing but the size is all ways 0px * 0px. If I do it in the html code it works fine. Is there any know reason why it might not work. If you need some of my code just ask.
okay here's some code...
var svg = document.createElement("svg");
svg.setAttribute("style", "border: 1px solid black");
svg.setAttribute("height",20);
svg.setAttribute("width",20);
document.getElementById("container").appendChild(svg);
I also tried slightly different code. Also giving it a border gives it a small width and height(not the right one)
回答1:
You can't create SVG elements with createElement, createElement is for html elements only. You must use createElementNS with the SVG namespace i.e.
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
回答2:
Maybe because your <svg>
is empty, try to add some content to your<svg>
.
var svg = document.createElement("svg");
svg.setAttribute("style", "border: 1px solid black");
svg.setAttribute("height",20);
svg.setAttribute("width",20);
svg.innerHTML = "Some content";
document.getElementById("container").appendChild(svg);
来源:https://stackoverflow.com/questions/34478416/svg-size-isnt-working-with-javascript