检索 CSS 是否需要 'getPropertyValue' 方法?

Is the 'getPropertyValue' method required for retrieving CSS?

如果我们只能使用 getComputedStyle 方法,你能告诉我为什么我们需要使用 getPropertyValue 方法吗?

例如,据我了解,这会起作用:

var s = getComputedStyle(element, null).opacity;

相当于以下内容:

var s = getComputedStyle(element, null).getPropertyValue('opacity');

我们可以在没有 getPropertyValue 的情况下使用 getComputedStyle 吗?

我认为它适用于不能用点符号表示的属性,例如 background-position。虽然我想这会提出问题 "why not use brackets notation, i.e. getComputedStyle(element, null)['background-position']?"。他们可能只是想要 class (CSSStyleDeclaration) 的 getter 方法。

根据旧 DOM L2 Style,不需要 getPropertyValue

The CSS2Properties interface represents a convenience mechanism for retrieving and setting properties within a CSSStyleDeclaration. The attributes of this interface correspond to all the properties specified in CSS2. Getting an attribute of this interface is equivalent to calling the getPropertyValue method of the CSSStyleDeclaration interface. Setting an attribute of this interface is equivalent to calling the setProperty method of the CSSStyleDeclaration interface.

但是,不需要实施来支持它,因此使用 getPropertyValue 更安全。

A conformant implementation of the CSS module is not required to implement the CSS2Properties interface.

但根据较新的 CSSOM,使用不带 getPropertyValue 的驼峰式大小写必须可行:

For each CSS property property that is a supported CSS property, the following partial interface applies where camel-cased attribute is obtained by running the CSS property to IDL attribute algorithm for property.

partial interface CSSStyleDeclaration {
    attribute DOMString _camel-cased attribute;
};

The camel-cased attribute attribute, on getting, must return the result of invoking getPropertyValue() with the argument being the result of running the IDL attribute to CSS property algorithm for camel-cased attribute.

Setting the camel-cased attribute attribute must invoke setProperty() with the first argument being the result of running the IDL attribute to CSS property algorithm for camel-cased attribute, as second argument the given value, and no third argument. Any exceptions thrown must be re-thrown.

因此,不再需要 getPropertyValue 来检索 CSS 值。