如果未通过createElementNS处理,为什么动态SVG无法工作 [英] Why won't dynamic SVG work if not handled via createElementNS

查看:95
本文介绍了如果未通过createElementNS处理,为什么动态SVG无法工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在普通JS中操作SVG,发现如果我不使用createElementNSsetAttributeNS之类的方法,它将无法达到预期的效果.

I was trying to manipulate SVG in plain JS and found that it won't behave as intended if I don't use methods like 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>

上面的标记效果很好.但是,如果您尝试通过以下代码添加另一个圆圈,则看不到它.

The above markup works perfectly. But if you try to add another circle via the following code, you won't see it.

var circle = createElement('circle');
circle.setAttribute('cx', 50);
....
document.getElementById('mysvg').appendChild(circle);

但是,如果您使用createElementNSsetAttributeNS,它将按预期工作.

But if you use createElementNS and setAttributeNS, it will work as expected.

更糟糕的是,createElementcreateElementNS都创建相同的DOM文本.

To be worst, both createElement and createElementNS create identical DOM text.

推荐答案

它不起作用,因为规范指出SVG元素必须存在于SVG命名空间中,并且createElement在html namepace中创建元素.解析器如何才能另外知道您是要创建一个html <a>元素来使用src属性,还是要创建一个需要`xlink:href属性的SVG <a>元素呢?

It doesn't work because the specifications say that SVG elements must exist in the SVG namespace and createElement creates elements in the html namepace. How would a parser know otherwise whether you wanted to create an html <a> element which works with a src attribute or a SVG <a> element for which an `xlink:href attribute is required.

在不对名称空间进行序列化的html中,外观看起来相同.在对名称空间进行序列化的XML中,它们不进行序列化.

In html where namespaces are not serialized things look the same. In XML where namespaces are serialized they don't.

HTML中的SVG看起来像这样...

SVG in html looks like this...

<svg id="mydsvg" width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>

SVG作为独立文档看起来像这样

SVG as a standalone document would look like this

<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>

圆继承了其父级的命名空间.

The circle inherits the namespace of its parent.

这篇关于如果未通过createElementNS处理,为什么动态SVG无法工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆