Javascript methods to get CSS attribute values: getComputedStyle and currentStyle
1. For the inline CSS style of the element (
hello
), you can Directly use element.style.color to directly obtain the value of the css attribute;
2. However, externally defined css styles cannot be obtained using this method, and IE and other standard browsers (Firefox , Chrome, Opera, Safari) use different methods. IE browser uses element.currentStyle, and W3C standard browser uses getComputedStyle to obtain it.
1. IE obtains the value of the CSS attribute defined outside the element: element.currentStyle
The currentStyle object returns the style sheet on the element, but the style object only returns the style sheet applied to the element through the style tag attribute. Inline styles.
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 ( red ) through a linked or embedded stylesheet, rather than inline, the object .currentStyle.color will return the correct color, while the object style.color will not Return value. However, if the user specifies
, both currentStyle and STYLE objects will return the value red.
The currentStyle object reflects the style priority in the style sheet. In HTML this order is:
1) Inline styles
2) Style sheet rules
3) HTML tag attributes
4) HTML tags The internal definition of
2. W3C gets the CSS attribute value defined externally by the element: window.getComputedStyle(element, pseudoElt)
element is required, HTML element
pseudoElt is required, and gets the pseudoElt of the element. Class Style
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;
}