For example, a set of style information is cascaded for an HTML element, in which the value of the width attribute is 80px. Then calling the script to read this value, the result is always an empty string, but in fact I want to get "80px". In response to this situation, David Flanagan gives a solution in the book "The Definitive Guide to JavaScript (Fifth Edition)".
The following is a translation for JavaScript: The Definitive Guide, 5th Edition Chapter16 Section4
Script-calculated styles
The style attribute of the HTML element is equivalent to the style HTML attribute, and as the style attribute Value, CSS2 property object only inline style information for such an element. This does not include any other styles within the CSS cascade. Sometimes you really want to know the exact style settings assigned to an element, while ignoring the styles within the cascade. All you want to do is calculate the style for the element. Unfortunately the name of the calculated styles is ambiguous; it relates to a calculation that is performed before the browser displays the element: all styles are tried to see if they are applicable to the element, and all applicable styles are merged into any content within the element. embedded style. This aggregated style information can be used to correctly render the element in the browser window. In the W3C standard, the API used to determine the calculated style of an element is the getComputedStyle() method of the window object. The first parameter of this method is the element whose style is expected to be calculated. The second parameter is any desired CSS pseudo-object, such as ":before" or ":after". You're probably not interested in the pseudo-object, but in Mozilla and Firefox's implementation of this method, the second parameter cannot be ignored. Otherwise, you will always find getComputedStyle() throwing null due to its second parameter. The return value of getComputedStyle() is a CSS2 property object that represents the style of all loaded elements or pseudo-objects. Unlike CSS2 property objects that can control embedded style information, the object returned by getComputedStyle() is read-only. IE does not support the getComputedStyle() method, but provides a simpler alternative. Each HTML element has a currentStyle attribute that controls its calculated style. The only drawback of IE's API is that it does not provide a way to query pseudo-object styles. As an example of computed styles, you can use the following cross-platform code to determine the font style in which an element is represented: