DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript克隆元素樣式的實現代碼
javascript克隆元素樣式的實現代碼
編輯:關於JavaScript     
復制代碼 代碼如下:
/**
* 克隆元素樣式
* @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));

演示:

[Ctrl+A 全選 注:如需引入外部Js需刷新才能執行]
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved