使用JavaScript创建SVG标记

使用JavaScript创建SVG标记,javascript,svg,Javascript,Svg,如何使用JavaScript创建SVG元素?我试过这个: var svg = document.createElement('SVG'); svg.setAttribute('style', 'border: 1px solid black'); svg.setAttribute('width', '600'); svg.setAttribute('height', '250'); svg.setAttribute('version', '1.1'); s

如何使用JavaScript创建SVG元素?我试过这个:

var svg = document.createElement('SVG');
    svg.setAttribute('style', 'border: 1px solid black');
    svg.setAttribute('width', '600');
    svg.setAttribute('height', '250');
    svg.setAttribute('version', '1.1');
    svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
document.body.appendChild(svg);
但是,它会创建一个零宽度和零高度的SVG元素。

您忘记了
SVG
元素和
xmlns
属性的名称

此外,
版本
被所有浏览器忽略

var svg=document.createElements(“http://www.w3.org/2000/svg“,“svg”);
setAttribute('style','border:1px纯黑');
setAttribute('width','600');
setAttribute('height','250');
svg.setAttributeNS(“http://www.w3.org/2000/xmlns/“,”xmlns:xlink“,”http://www.w3.org/1999/xlink");

document.body.appendChild(svg)
.createElements
svg
路径
元素所需的方法。下面的例子

var svg=document.createElements(“http://www.w3.org/2000/svg“,“svg”);
var path1=document.createElements(“http://www.w3.org/2000/svg“,‘路径’”;
var path2=document.createElements(“http://www.w3.org/2000/svg“,‘路径’”;
setAttribute(“aria hidden”、“true”);
setAttribute('viewbox','0 0 24');
setAttribute('width','24px');
setAttribute('height','24px');
路径1.setAttribute('d','m0h24v24h0z');
路径1.setAttribute('fill','none');
4.48 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 12 12 12 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2.2 2 2 2 2 2 2 2 2 2 2 2.2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1954.0657.4102.08-.83.97-2.15.39z’;
路径2.setAttribute('fill','#2962ff');
appendChild(路径1);
appendChild(路径2);

document.body.appendChild(svg)您使用什么浏览器执行此操作?“svg:svg”?简单的旧“svg”也可以正常工作。另外,“版本”被所有浏览器忽略,所以添加它有点浪费。谢谢@ErikDahlström,更正。那么svg.setAttributeNS(“)呢;?名称空间真的有必要吗?如果您要使用
xlink:href
标记,这是绝对必要的。否则,就没有那么多。对于那些在开发工具中查看DOM的人来说,不要被愚弄-如果您使用
innerHTML
outerHTML
直接分配svg标记,您将看到
xmlns=http://www.w3.org/2000/svg
在树中的标记表示中。如果您使用
createElements
,您将看不到它,但它仍然存在!您必须使用
createElements
,否则ns将不存在。我的关键问题是,在使用JS并添加
路径时,您不需要使用的显式ns声明de>innerHTML
,它会继承。如果使用
createElement
,它不会继承,因此您还必须使用
CreateElements