First, getComputedStyle () usage
document.defaultView.getComputedStyle (element [, pseudo-element]);
window.getComputedStyle (element [, pseudo-element]);
The first is to have two parameters, the element and the pseudo-class. The second parameter is not required. You can ignore or pass in null when not querying the pseudo-type elements.
Example of use:
let my_div = document.getElementById ("myDiv");
let style = window.getComputedStyle (my_div, null);
About defaultView quote the MDN description of defaultView:
In many online demo code, getComputedStyle is called via the document.defaultView object. In most cases, this is not needed because it can be called directly from the window object. But there is a case where you must use the defaultView, which is to access the style (iframe) in the child frame on Firefox 3.6.
And in addition to IE8 browser document.defaultView === window returns false, other browsers (including IE9) return true. So just use window directly in the future, instead of typing that long code.
Second, the return value
The object returned by getComputedStyle is an object of type CSSStyleDeclaration. When fetching data, you can directly fetch the data according to the method of attributes, such as style.backgroundColor. It should be noted that the key name of the returned object is the camel case of css, background-color-> backgroundColor.
var float_property = window.getComputedStyle.style; // chrome and Firefox support
This cannot be used in any version of IE, and only styleFloat is supported in IE 8. This is mentioned in the compatibility issue below.
Similarities and differences with style
The same thing about getComputedStyle and element.style is that both return CSSStyleDeclaration objects. It is worth using the CSS camel-case method to get the corresponding attributes. Both need to pay attention to the float attribute.
The difference is:
element.style reads only the inline style of the element, that is, the style written on the element's style property; and the style read by getComputedStyle is the final style, including inline style, embedded style, and external style.
element.style supports both reading and writing, we can rewrite the style of the element through element.style. And getComputedStyle only supports read and not write. We can read the style by using getComputedStyle and modify the style by element.style
We can read the style by using getComputedStyle and modify the style by element.style.
Regarding the compatibility of getComputedStyle, this property is supported in Chrome and Firefox. At the same time, IE 9 10 11 also supports the same feature. IE 8 does not support this feature. IE 8 supports the element.currentStyle property. The value returned by this property is basically the same as that returned by getComputedStyle, except for the support of float. IE 8 supports styleFloat. This requires attention.