1

我试图弄清楚是否有一种更简单的方法来保留我将更改的 CSS 属性列表,然后使用 jquery 恢复 JSON 对象中的任何元素,而无需编写下面的 getAttributes 之类的函数。

假设我有一个包含 3 个属性的数组,我想为 element 保留:

我可以把它写成一个函数,它看起来像这样:

  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);

有任何想法吗?

4

1 回答 1

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);
于 2013-04-27T19:18:02.373 回答