我试图在纯 JS 中操作 SVG,发现如果我不使用类似的方法,它就不会按预期运行createElementNS
and setAttributeNS
.
<svg id="mydsvg" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
上面的标记工作得很好。但是,如果您尝试通过以下代码添加另一个圆圈,您将看不到它。
var circle = createElement('circle');
circle.setAttribute('cx', 50);
....
document.getElementById('mysvg').appendChild(circle);
但如果你使用createElementNS
and setAttributeNS
,它将按预期工作。
最糟糕的是,两者createElement
and createElementNS
创建相同的 DOM 文本。
它不起作用,因为规范规定 SVG 元素必须存在于 SVG 命名空间中,而 createElement 在 html 命名空间中创建元素。否则解析器如何知道您是否想要创建 html<a>
与 src 属性或 SVG 一起使用的元素<a>
需要 `xlink:href 属性的元素。
在 html 中,命名空间没有序列化,事情看起来是一样的。在 XML 中,名称空间是序列化的,但它们却没有。
html 中的 SVG 看起来像这样......
<svg id="mydsvg" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
SVG 作为独立文档看起来像这样
<svg xmlns="https://www.w3.org/2000/svg" id="mydsvg" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
该圆继承其父级的命名空间。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)