Use DOM to manipulate inline styles

Use DOM to manipulate css

Modify the style of the element through JS

  • Syntax: element.style.style name=style value
  • Note: If the CSS style name contains -, this name is illegal in JS, such as background-color. You need to modify this style name to camel case naming, remove -, and then capitalize the letter after-
  • The styles we set through the style attribute are all inline styles, and inline styles have a higher priority, so styles modified through JS are often displayed immediately
  • But if you write in the style of! Important, the style of this time there will be the highest priority even if JS can not be covered by this style, this time will result in failure JS modify the style so try not to add style! Important
			   box1.style.width = "300px";
               box1.style.height = "300px";
               box1.style.backgroundColor = "yellow";

Read the style of the element

alert(box1.style.width);

Get the currently displayed style of the element

  • Syntax: element.currentStyle.style name
  • It can be used to read the style of the current element being displayed
  • If the style is not set for the current element, get its default value
  • currentStyle is only supported by IE browser, not other browsers

Can be used in other browsers

  • getComputedStyle() method to get the current style of the element
  • This method is a window method and can be used directly
  • Two parameters are required. The first one: the element to get the style. The second one: you can pass a pseudo-element, generally null
  • This method returns an object that encapsulates the style corresponding to the current element
  • You can read the style by object.style name
  • If the obtained style is not set, it will get the real value instead of the default value. For example: if width is not set, it will not get auto, but a length
  • But this method does not support IE8 and below browsers
  • The styles read through currentStyle and getcomputedStyle() are read-only and cannot be modified. If you modify it, you must pass the style attribute
var obj = getComputedStyle(box1,null);
              alert(obj.width);
              alert(obj.backgroundColor);

Guess you like

Origin blog.csdn.net/weixin_48769418/article/details/114527414