getcomputedstyle()的jQuery等效方法

26

我在一个JavaScript插件中找到了这个getComputedStyle polyfill。

if (!computed) {
  window.getComputedStyle = function(el) {
    this.el = el;
    this.getPropertyValue = function(prop) {
      var re = /(\-([a-z]){1})/g;
      if (prop === "float") {
        prop = "styleFloat";
      }
      if (re.test(prop)) {
        prop = prop.replace(re, function () {
          return arguments[2].toUpperCase();
        });
      }
      return el.currentStyle[prop] ? el.currentStyle[prop] : null;
    };
    return this;
  };
}

是否有jQuery中与getcomputedstyle()等效的函数?


4
http://api.jquery.com/css/? - Bergi
1个回答

43

你可以使用.css()方法的getter版本。

来自文档:

.css()方法是一种方便的方式来获取第一个匹配元素的样式属性,特别是考虑到不同浏览器访问大多数属性的不同方式(标准浏览器中的getComputedStyle()方法与Internet Explorer中的currentStyle和runtimeStyle属性)以及浏览器用于某些属性的不同术语。

例如:

$(el).css('color')

3
这是否考虑了浏览器默认设置和/或用户自定义样式?我猜这就是@Arya所说的“计算样式”的意思。 - Plato
5
从文档中得知:“* .css()方法是一种方便的方式,用于从第一个匹配元素获取样式属性,特别是考虑到浏览器访问大多数这些属性的不同方式(基于标准的浏览器中的getComputedStyle()方法与Internet Explorer中的currentStyle和runtimeStyle属性)以及浏览器对某些属性使用不同术语*”。 - Bergi
@Arya 注意,你的polyfill可能会弊大于利——最好让jQuery按照它自己的方式运行。 - Alnitak
1
看起来它确实从用户代理样式表获取属性:http://jsfiddle.net/c8RDW/ - Plato
3
jQuery和getComputedStyle是不同的...不一样。例如,尝试使用$('p:before').css('color','red')是无效的...只有JavaScript是真正有效的。jQuery只是一个插件。 - KingRider
CSS根本不是解决方案。例如,如何获取半透明元素的RGB颜色数据?我想我们仍然需要在这里使用本机JS。 - Andrey Merkulov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接