JavaScript克隆元素样式
这是一个实验用的玩意,它可以克隆指定元素的最终样式,并包装成一个css类,它还可以证明Oprea 11.10 是个混球:
01 |
/** |
02 |
* 克隆元素样式 |
03 |
* @param {HTMLElement} 被克隆的元素 |
04 |
* @param {Boolean} 是否启用缓存(默认true) |
05 |
* @return {String} css类名 |
06 |
*/ |
07 |
var cloneStyle = (function (doc) { |
08 |
var rstyle = /^(number|string)$/, |
09 |
cloneName = '${cloneName}', |
10 |
sData = {}, |
11 |
addHeadStyle = function (content) { |
12 |
var style = sData[doc]; |
13 |
if (!style) { |
14 |
style = sData[doc] = doc.createElement('style'); |
15 |
doc.getElementsByTagName('head')[0].appendChild(style); |
16 |
}; |
17 |
style.styleSheet && (style.styleSheet.cssText += content) || style.appendChild(doc.createTextNode(content)); |
18 |
}, |
19 |
getStyle = 'getComputedStyle' in window ? function (elem, name) { |
20 |
return getComputedStyle(elem, null)[name]; |
21 |
} : function (elem, name) { |
22 |
return elem.currentStyle[name]; |
23 |
}; |
24 |
25 |
return function (source, cache) { |
26 |
if (!cache && source[cloneName]) return source[cloneName]; |
27 |
28 |
var className, name, |
29 |
cssText = [], |
30 |
sStyle = source.style; |
31 |
32 |
for (name in sStyle) { |
33 |
val = getStyle(source, name); |
34 |
if (val !== '' && rstyle.test(typeof val)) { |
35 |
name = name.replace(/([A-Z])/g,"-$1").toLowerCase(); |
36 |
cssText.push(name); |
37 |
cssText.push(':'); |
38 |
cssText.push(val); |
39 |
cssText.push(';'); |
40 |
}; |
41 |
}; |
42 |
cssText = cssText.join(''); |
43 |
44 |
source[cloneName] = className = 'clone' + (new Date).getTime(); |
45 |
addHeadStyle('.' + className + '{' + cssText + '}'); |
46 |
47 |
return className; |
48 |
}; |
49 |
}(document)); |
DEMO: http://www.planeart.cn/demo/cloneStyle
发表评论