Easy Tutorial
❮ 9Patch 9 Remove Black Line Android Tutorial Shadowlayer ❯

Usage of window.getComputedStyle() Method

Category Programming Technology

I. Usage of getComputedStyle()

document.defaultView.getComputedStyle(element[,pseudo-element]);  
or
window.getComputedStyle(element[,pseudo-element]);

The method has two parameters: the element and the pseudo-element. The second parameter is optional and can be omitted or passed as null when not querying pseudo-element styles.

Example of usage:

let my_div = document.getElementById("myDiv");
let style = window.getComputedStyle(my_div, null);

Regarding the defaultView, here is a description from MDN:

defaultView

In many online demo codes, getComputedStyle is called through the document.defaultView object. This is generally unnecessary as it can be directly called through the window object. However, there is a case where you must use defaultView, which is when accessing styles within sub-frames (iframe) in Firefox 3.6.

Additionally, except in IE8 where document.defaultView === window returns false, other browsers (including IE9) return true. Therefore, it is better to directly use window without typing the longer code.


II. Return Value

getComputedStyle returns an object of type CSSStyleDeclaration. When retrieving data, you can directly access properties like style.backgroundColor. Note that the keys of the returned object are in camelCase for CSS, such as background-color -> backgroundColor.

Special attention should be given to the float property. According to "Advanced JavaScript", float is a reserved keyword in JS. According to the DOM2 specification, to get the float property of an element, you should use cssFloat. However, Chrome and Firefox support the float property directly.

var float_property = window.getComputedStyle.style; // Supported in Chrome and Firefox

This cannot be used in any version of IE, and only supports styleFloat in IE8, as discussed in the compatibility issues below.


III. Differences from style

Both getComputedStyle and element.style return a CSSStyleDeclaration object and both use camelCase for CSS property names, including the float property.

The differences are:


IV. Compatibility

Regarding the compatibility of getComputedStyle, it is supported in Chrome and Firefox, as well as IE 9, 10, and 11. IE 8 does not support this feature. IE 8 supports the element.currentStyle property, which returns values similar to getComputedStyle, except for the float property where IE 8 supports styleFloat.

Original Source: https://blog.csdn.net/s110902/article/details/73312802?locationNum=12&fps=1

** Click to Share Notes

Cancel

-

-

-

❮ 9Patch 9 Remove Black Line Android Tutorial Shadowlayer ❯