javascript複製元素樣式的實現代碼

來源:互聯網
上載者:User

複製代碼 代碼如下:/**
* 複製元素樣式
* @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));

示範:<meta http-equiv="Content-Type" content="text/html; charset=gb2312"><br /><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><p><button onclick="document.getElementById('span').className = cloneStyle(document.getElementById('div'));">複製div的最終樣式到span</button> </p>我是DIV標籤<p>我是SPAN標籤<br />

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.