Javascript is a great way to capture element styles

  • 2020-03-30 02:48:26
  • OfStack

Javascript gets the CSS property value methods: getComputedStyle and currentStyle

1. Inline CSS styles for elements (< Div style = "color: # 369" > Hello< / div>) , you can directly use to directly get the value of CSS properties;

2. However, for externally defined CSS styles, this method is not available, and Internet explorer USES different methods from other standard browsers (Firefox, Chrome, Opera, Safari). Internet explorer USES element.currentstyle, and W3C standard browsers use getComputedStyle.

1. IE gets the CSS property value defined outside the element: element.currentstyle

The currentStyle object returns the style sheet on the element, but the style object only returns the inline style applied to the element through the style tag attribute.

Therefore, the style value obtained with the currentStyle object may be different from the style value obtained with the style object.

For example, if the color property value of a paragraph is set to red via a link or embedded style sheet instead of inline, the object. Currentstyle.color will return the correct color, while the object style.color cannot. However, if the user specifies < P STYLE = "color: 'red'" > , currentStyle and STYLE objects both return the value red.
The currentStyle object reflects the style precedence in the style sheet. In HTML this order is:

1) inline style

2) style sheet rules

3) HTML tag attributes

4) internal definition of HTML tags

2. W3C gets the CSS attribute value defined outside the element: window.getcomputedstyle (element, pseudoElt)
Element, HTML element
PseudoElt is optional and gets the pseudo-class style of the element

function getStyle(node, property){ 
if ([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; 

Related articles: