Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

javascript - Why won't dynamic SVG work if not handled via createElementNS

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...