2013-04-27 100 views
1

我想弄清楚是否有更簡單的方法來保存CSS屬性列表我將更改,然後恢復使用JSON對象中的任何元素jquery無需編寫如下getAttributes函數。如何使用jquery獲取元素的css屬性列表

可以說我有3個屬性的陣列,我想保留的元素:

我可以這樣寫一個函數就應該是這樣的:

function getAttributes(elem, attrs){ 
    var obj={}; 
    $.each(attrs,function(i,attr){ 
     obj[attr]=$(elem).css(attr); 
    }); 
    return obj; 
    } 

    oldAttrs=getAttributes('input',['color','background-color','font-size']); 

    $('input').css({color:'green', 'background-color':'blue', fonts-size:'10px'}); 
    ......  

後來,我就可以只做這個優雅的方法來恢復:

$('input').css(oldAttrs); 

任何想法?

回答

0

這裏沒有jQuery函數,但靜態方法window.getComputedStyle適用於所有現代瀏覽器和IE9。

var cachedStyle = window.getComputedStyle(domElement); 

// later 
$(domElement).css(cachedStyle); 

更新:如果你只希望保留一些樣式屬性

你不能選擇你開始使用getComputedStyle哪些屬性,但您可以選擇您在使用哪些$的.css。假設您只想保留背景顏色,寬度和左邊距(出於某種原因):

var cachedStyle = window.getComputedStyle(domElement); 
var propNamesToPreserve = ['backgroundColor','width','marginLeft']; // use the JS-style camelcased attributes, not hyphen-separated CSS properties 

var preservedProps = {}; 
$.each(propNamesToPreserve, function(ix, name) { 
    preservedProps[name] = cachedStyle[name]; 
}); 

//later 
$(domElement).css(preservedProps); 
+0

#1。這保留了每個屬性。如果我想要的是保留3或4個屬性,是否有懲罰? #2。通過現代瀏覽器,你的意思是HTML5? – user603749 2013-04-27 19:32:17

+0

無論doctype是HTML4,XHTML還是HTML5,它都可以工作。通過現代瀏覽器,我只是說它不適用於IE8。 – zetlen 2013-04-27 19:44:07

+0

只有3或4個屬性沒有性能損失 - 事實上,它可能會更快,因爲'$ .fn.css'遍歷所有對象屬性。我會用一個解決方案更新我的答案。 – zetlen 2013-04-27 19:45:55

相關問題