Javascript method to get CSS attribute value: getComputedStyle and currentStyle
1. For the inline CSS style of the element (<div style="color:#369">hello</div>), you can directly use element.style.color to directly obtain the value of the css attribute;
2. However, it is impossible to obtain the externally defined css styles. Moreover, the methods used by IE browser are different from other standard browsers (Firefox, Chrome, Opera, Safari). IE browser uses element.currentStyle, and W3C standard browser uses getComputedStyle to obtain.
1. IE gets the CSS attribute value defined externally in the element: element.currentStyle
The currentStyle object returns the stylesheet on the element, but the style object only returns the embedded style applied to the element through the style tag 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 property value of the paragraph is set to red ( red ) through a link or embed stylesheet instead of embedded, the object .currentStyle.color will return the correct color, and the object style.color cannot return the value. However, if the user specifies <P STYLE="color:'red'">, 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 style
2) Stylesheet rules
3) HTML tag attributes
4) Internal definition of HTML tags
2. W3C obtains the CSS attribute value defined externally: window.getComputedStyle(element, pseudoElt)
Element required, HTML element
pseudoElt is required to get the pseudo-class style of the element
The code copy 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;
}