即使在使用命名空间之后,也无法附加到SVG
问题描述:
我试图使用JavaScript将circle
附加到svg
元素。当我创建这个圈子时,我发现你应该使用createElementNS
而不是createElement
。我这样做了,圆圈确实出现在HTML中,但它仍然没有出现在页面中。这里是我的代码:即使在使用命名空间之后,也无法附加到SVG
let ns = 'http://www.w3.org/2000/svg';
let svg = document.getElementsByTagName('svg')[0];
let circle = document.createElementNS(ns, 'circle');
circle.setAttributeNS(ns, 'cx', 100);
circle.setAttributeNS(ns, 'cy', 100);
circle.setAttributeNS(ns, 'r', 10);
circle.style.fill = 'red';
svg.appendChild(circle);
输出是:
<svg><circle cx="100" cy="100" r="10" style="fill: red;"></circle></svg>
但有一种观点是空的。看到Codepen here.
答
使用createElementNS
你不需要setAttributeNS
创建圈子元素后,你应该使用setAttribute
功能:
var ns = 'http://www.w3.org/2000/svg';
var svg = document.getElementsByTagName('svg')[0];
var circle = document.createElementNS(ns, 'circle');
circle.setAttribute('cx', 100);
circle.setAttribute('cy', 100);
circle.setAttribute('r', 10);
circle.style.fill = 'red';
svg.appendChild(circle);
svg{ width: 100%; height: 100%; background-color: blue; }
<svg></svg>