有時候我們需要把 A 元素身上「最終生效」的樣式搬到 B 元素上,而不是搬類別名稱。做法是把 computed style 讀出來,組成一條 CSS 規則,塞進動態產生的 <style> 標籤裡。
/**
* 克隆元素樣式
* @param {HTMLElement} 被克隆的元素
* @param {Boolean} 是否啟用緩存(默認true)
* @return {String} css類名
*/
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.cssText += 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));
為什麼要過濾型別。 for...in 遍歷 style 時會撈到大量非 CSS 值的成員,用 rstyle 只保留 number 與 string,可以濾掉函式與物件。
駝峰轉連字號。 getComputedStyle 回傳的鍵名是駝峰式(backgroundColor),寫進樣式表前必須轉成 background-color。
兩套讀寫介面。 標準瀏覽器用 getComputedStyle,舊 IE 走 currentStyle;寫入時也有 styleSheet.cssText 與 appendChild(textNode) 兩種路徑,這裡用 && / || 短路把它們併成一行。
快取。 把產生的類別名掛在來源元素上,第二次呼叫同一元素就直接回傳,不必重算。第二個參數傳 false 可強制重算。
<!DOCTYPE HTML>
<html>
<head>
<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>
</head>
<body>
<button onclick="document.getElementById('span').className = cloneStyle(document.getElementById('div'));">克隆div的最終樣式到span</button>
<div id="div">我是DIV標簽</div>
<span id="span">我是SPAN標簽</span>
</body>
</html>
點下按鈕後,span 會套用一個新產生的類別,內容就是 div 當前所有 computed style 的序列化結果。要注意這複製的是計算後的具體數值(例如 width:300px 而非原本的 150px 語意),因此它比較適合「讓兩個元素長得一樣」這類需求,而不適合當作樣式繼承機制。