I have an html file, I'm adding am element to it dynamically, then a rectangle. Works well in the different browsers (ignoring IE). When I try to use the same method to dynamically create an element, it does not work in Chrome or Safari, only in Opera. Is my syntax wrong, or does webkit probably just not support adding elements at runtime? (the same element works fine if I declare it as tags up-front instead). Maybe I'm not supposed to use appendChild() with these types of nodes? Here's what I have, you should be able to dump it into an html file and run it. If anyone has any idea if there's a way around this, it'd be great:
<html>
<head>
<script>
window.onload = function() {
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
svg.setAttribute('version', '1.1');
svg.setAttribute('width', '800px');
svg.setAttribute('height', '400px');
document.body.appendChild(svg);
var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute("id", "myrect");
rect.setAttribute("fill","red");
rect.setAttribute("stroke","black");
rect.setAttribute("stroke-width","5");
rect.setAttribute("x", "100");
rect.setAttribute("y", "100");
rect.setAtt开发者_开发问答ribute("width", "100");
rect.setAttribute("height", "50");
svg.appendChild(rect);
var anim = document.createElementNS('http://www.w3.org/2000/svg','animate');
anim.setAttribute("attributeName", "width");
anim.setAttribute("from", "100");
anim.setAttribute("to", "400");
anim.setAttribute("dur", "10s");
anim.setAttribute("begin", "0s");
anim.setAttribute("fill", "freeze");
rect.appendChild(anim);
}
</script>
</head>
<body>
</body>
You really should use setAttributeNS(null, ...)
when using namespace calls like document.createElementNS()
.
From xmlgraphics.apache.org/batik/faq.html
However, it is important to know that some implementations make a difference between setAttribute(x, y) and setAttributeNS(null, x, y), so it is good practice to use setAttributeNS which is the only guaranteed interoperable way of setting attributes in a namespace aware DOM implementation.
Ughh this looks like a bug in webkit. You have to call node.beginElement() to get the animation to start, but in webkit it doesn't work, appears in the bug tracker.
Blast.
精彩评论