Copy codeThe Code is as follows:
/**
* Clone element styles
* @ Param {HTMLElement} the cloned Element
* @ Param {Boolean} whether to enable cache (true by default)
* @ Return {String} css Class Name
*/
Var cloneStyle = (function (doc ){
Var rstyle =/^ (number | string) $ /,
CloneName = '$ {cloneName }',
SData = {},
AddHeadStyle = function (content ){
Var style = sData [doc];
If (! Style ){
Style = sData [doc] = doc. createElement ('style ');
Doc. getElementsByTagName ('head') [0]. appendChild (style );
};
Style. styleSheet & (style.styleSheet.css Text + = content) | style. appendChild (doc. createTextNode (content ));
},
GetStyle = 'getcomputedstyle' in window? Function (elem, name ){
Return getComputedStyle (elem, null) [name];
}: Function (elem, name ){
Return elem. currentStyle [name];
};
Return function (source, cache ){
If (! Cache & source [cloneName]) return source [cloneName];
Var className, name,
CssText = [],
SStyle = source. style;
For (name in sStyle ){
Val = getStyle (source, name );
If (val! = ''& Rstyle. test (typeof val )){
Name = name. replace (/([A-Z])/g, "-$1"). toLowerCase ();
CssText. push (name );
CssText. push (':');
CssText. push (val );
CssText. push (';');
};
};
CssText = cssText. join ('');
Source [cloneName] = className = 'clone '+ (new Date). getTime ();
AddHeadStyle ('.' + className + '{' + cssText + '}');
Return className;
};
} (Document ));
Demo:
<! Doctype html> <ptml> <pead> <meta http-equiv = "Content-Type" content = "text/html; charset = gb2312 "> <title> cloneStyle </title> <style> div {width: 150px; margin: 20px; background: # FBFCFD; border: 1px solid # D0DCE8; text-align: center; line-height: 3em; font-size: 1.5em ;}. skin {-webkit-border-radius: 5px;-moz-border-radius: 5px; border-radius: 5px ;}# div {width: 300px; height: 300px ;} span {border: 1px solid # D0DCE8; color: # F00 ;}</style> </pead> <body> <button onclick = "document. getElementById ('span '). className = cloneStyle (document. getElementById ('div '); "> clone the final style of the div to span </button> I am a div tag, I am a SPAN tag </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]