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
285 views
in Technique[技术] by (71.8m points)

javascript - How can I programmatically copy all of the style attributes from one DOM element to another

I have a page with two frames, and I need to (via javascript) copy an element and all of its nested elements (it's a ul/li tree) and most importantly it's style from one frame to the other.

I get all the content via assigning innerhtml, and I am able to position the new element in the second frame with dest.style.left and dest.style.top and it works. But I'm trying to get all the style information and nothing's happening.

I'm using getComputedStyle to get the final style for each source element as I loop through each node then and assigning them to the same position in the destination nodelist and nothing happens to visually change the style.

What am I missing?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

With getComputedStyle, you can get the cssText property which will fetch the entire computed style in a CSS string:

var completeStyle = window.getComputedStyle(element1, null).cssText;
element2.style.cssText = completeStyle;

Unfortunately, getComputedStyle isn't supported by Internet Explorer, which uses currentStyle instead. Doubly unfortunate is the fact that currentStyle returns null for cssText, so the same method cannot be applied to IE. I'll try and figure something out for you, if nobody beats me to it :-)


I thought about it and you could emulate the above in IE using a for...in statement:

var completeStyle = "";
if ("getComputedStyle" in window)
    completeStyle = window.getComputedStyle(element1, null).cssText;
else
{
    var elStyle = element1.currentStyle;
    for (var k in elStyle) { completeStyle += k + ":" + elStyle[k] + ";"; }
}

element2.style.cssText = completeStyle;

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

...