svg size isn't working with javascript

大城市里の小女人 提交于 2020-07-29 20:15:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!