开发者

SVG: compact way to create slightly different elements?

I'm creating several elements which are almost identical paths, with a long list of co-ordinates. Is there a compact way to create one element, and to to make slightly different copies of it?

The elements are created by 'createElementNS'. The obvious (I think) answer is to clone the first element into a new element, and to set only the attributes in the second element which have changed. This works in Chrome and IE9, but not in FF4 or Opera.

Another obvious solution is just to copy the first element into a var, and to set the changed attributes in the var. This doesn't work in Chrome or FF.

I could possibly create a new element via createElementNS, and copy all the attributes in from the old element, but I don't know of a way to cycle through all attributes, which would help.

This is an example of the almost-working clone code:


obj = svgDocument.createElementNS(svgn开发者_高级运维s, "path");
obj.setAttributeNS(null, "id", "pbox1");
...lots more attributes set
svgDocument.documentElement.appendChild(obj);

// now try to clone and copy:
var obj2 = obj.cloneNode(true);
obj2.setAttributeNS(null, "id", "pbox2");
...change a few obj2 attributes
svgDocument.documentElement.appendChild(obj2);

Any ideas?

Thanks -

Al


var templateElement =  document.createElement(// create template element);

var firstElement = templateElement.cloneNode(true) // the true make sure it clones all child nodes
var firstElement.setAttribute()// change what you need

and so on for as many elements as you need.


aaah.. stupid typo on my part; sorry. The code I posted above was correct, but I didn't show the other clones underneath. On the final one, I put in var obj10 = obj.cloneNode() , leaving out the 'true'. It looks like FF4 and Opera got the right answer, and Chrome and IE9 copied all the attributes anyway.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜