This article describes how to use javascript to obtain element styles. For more information, see getComputedStyle and currentStyle.
1. inline CSS styles for elements (
Hello
), You can directly use element. style. color to directly obtain the css attribute value;
2. however, this method cannot be used for externally defined css styles, and IE and other standard browsers (Firefox, Chrome, Opera, Safari) use different methods. ie uses element. currentStyle, which is obtained by the W3C standard browser using getComputedStyle.
1. IE gets the CSS attribute value defined externally by the element: element. currentStyle
The currentStyle object returns the style table on the element, but the style object only returns the embedded style applied to the element through the style label attribute.
Therefore, the style value obtained through the currentStyle object may be different from the style value obtained through the style object.
For example, if the color attribute value of a paragraph is set to red through a link or embedded style sheet, rather than embedded, the object. currentStyle. color returns the correct color, and the object style. color cannot return values. However, if you specify
, CurrentStyle and STYLE objects both return red values.
The currentStyle object reflects the style precedence in the style sheet. In HTML, the order is:
1) embedded Style
2) style sheet rules
3) HTML tag attributes
4) Internal definition of HTML tags
2. W3C: window. getComputedStyle (element, pseudo doelt)
Required for element, HTML element
Required. Pseudo-class style of the element.
The Code is as follows:
Function getStyle (node, property ){
If (node. style [property]) {
Return node. style [property];
}
Else if (node. currentStyle ){
Return node. currentStyle [property];
}
Else if (document. defaultView & document. defaultView. getComputedStyle ){
Var style = document. defaultView. getComputedStyle (node, null );
Return style. getPropertyValue (property );
}
Return null;
}