[英]How do I clone an HTML element's style object using JavaScript or jQuery?
我正在嘗試克隆元素的樣式 object 。 這應該允許我在更改它們后重置所述元素的 styles。
例如:
el.style.left; // 50px
curr_style.left; // 50px;
/*
Modify the elements style.
The cloned style should still hold the original properties from when it was cloned.
*/
el.style.left = '20px';
curr_style.left // should still return 50px.
我首先嘗試通過將變量分配給 el.style 的值來復制它。 不幸的是,這通過引用指向它,並且樣式的任何更改都反映在克隆的 object 中。
我的其他嘗試涉及使用 jQuery 的 object 擴展方法來創建這樣的副本:
var curr_style = $.extend( {}, el.style );
這似乎不起作用,因為 curr_style.left 等返回未定義。
任何幫助,將不勝感激!
我最終這樣做是為了檢索每個屬性:(基於@Raynos 的建議)
$.fn.getStyle = function(){
var style,
el = this[0];
// Fallbacks for old browsers.
if (window.getComputedStyle) {
style = window.getComputedStyle( el );
} else if (el.currentStyle) {
style = $.extend(true, {}, el.currentStyle);
} else {
style = $.extend(true, {}, el.style);
}
// Loop through styles and get each property. Add to object.
var styles = {};
for( var i=0; i<style.length; i++){
styles[ style[i] ] = style[ style[i] ];
}
return styles;
};
var curr_style;
if (window.getComputedStyle) {
curr_style = window.getComputedStyle(el);
} else if (el.currentStyle) {
curr_style = $.extend(true, {}, el.currentStyle);
} else {
throw "shit browser";
}
style
具有不可枚舉的屬性,這使得.extend
失敗。 您想使用getComputedStyle
方法獲取元素的 styles。
您還希望通過擴展具有可枚舉屬性的el.currentStyle
來支持舊版本的 IE。
第一個參數(當設置為true
時)告訴 jQuery 進行深度克隆。
為了簡單地重置 styles,我建議只使用 object style
的cssText
(另見MDN )屬性。 這適用於所有主要瀏覽器,並且非常簡單。
jsFiddle:
http://jsfiddle.net/timdown/WpHme/
示例代碼:
// Store the original style
var originalCssText = el.style.cssText;
// Change a style property of the element
el.style.fontWeight = "bold";
// Now reset
el.style.cssText = originalCssText;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.