Is the 'getPropertyValue' method required for retrieving CSS?

青春壹個敷衍的年華 提交于 2019-12-30 17:55:23

问题


Could you tell me why we need to use the getPropertyValue method if we can use only the getComputedStyle one?

For example, this will work, as far as I understand:

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

Which is equivalent to the following:

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

Can we use getComputedStyle without getPropertyValue?


回答1:


According to the old DOM L2 Style, getPropertyValue was not required:

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.

However, implementations were not required to support it, so using getPropertyValue was safer.

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

But according to the newer CSSOM, using camel-case without getPropertyValue must work:

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.

Therefore, getPropertyValue is no longer necessary to retrieve CSS values.




回答2:


I believe it is for properties that can't be dot-notationed, like background-position. Though I suppose that brings up the question "why not use brackets notation, i.e. getComputedStyle(element, null)['background-position']?". It's possible they just wanted a getter method for the class (CSSStyleDeclaration).



来源:https://stackoverflow.com/questions/31506401/is-the-getpropertyvalue-method-required-for-retrieving-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!