jquery等效于getcomputedstyle()

18 javascript jquery function

我在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;
  };
}
Run Code Online (Sandbox Code Playgroud)

getcomputedstyle()是否有任何jQuery等价物;

Aru*_*hny 34

您可以使用.css()的getter版本.

来自doc

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

喜欢

$(el).css('color')
Run Code Online (Sandbox Code Playgroud)

  • @Plato:来自文档:"*.css()方法是从第一个匹配元素获取样式属性的便捷方法,特别是考虑到浏览器访问大多数这些属性的不同方式(getComputedStyle()方法)基于标准的浏览器与Internet Explorer中的currentStyle和runtimeStyle属性)以及浏览器用于某些属性的不同术语*" (4认同)
  • 但这是否考虑了浏览器默认值和/或用户 CSS?我怀疑这就是@Arya 正在寻找的“计算风格” (3认同)
  • jQuery x getComputedStyle 是不同的......不一样。例如,尝试 `$('p:before').css('color','red')` 不起作用......只有 javascript 才是真正的工作。jQuery 只是插件。 (3认同)