如何使用jquery获取元素的css属性列表

时间:2013-04-27 19:12:41

标签: jquery css list

我试图弄清楚是否有更简单的方法来保存我将更改的CSS属性列表,然后使用jquery恢复JSON对象中的任何元素,而不必编写下面的getAttributes等函数。 / p>

假设我有一个包含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);

有什么想法吗?

1 个答案:

答案 0 :(得分: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);
相关问题