JS Instance code for getting and modifying element styles

  • 2021-07-09 06:44:41
  • OfStack

1. Get the element style:

The element inline style can be obtained through the style attribute of the element. The style property is an object that includes a series of style properties. For example: color, backgourdColor.

The above-mentioned element style is obtained through style attribute, which is not recommended.

The following 1 code can get the runtime style of the element, that is, the global style. This way, you can dynamically get the style of elements, such as element size.


// node Element node whose calculation style will be obtained 
// attr:  Style attribute name 
function getCurrentStyle(node, attr) {
  var style = null;
  //dom Standard mode 
  if(window.getComputedStyle) {
    style = window.getComputedStyle(node, null);
  }
  else{
    style = node.currentStyle; //ie Mode 
  }
  
  return style[attr];
}

2. Modify the element style

Directly through the element's style attribute, for example: p. style. backgroundColor = "red"

Note: There is a difference between the attribute name and the defined element attribute name when the element style is obtained or modified by the above method. For example, if the background color is defined by background-color of css, the first letter after the '-' symbol needs to be converted to size when obtaining or modifying this style attribute in js.


Related articles: