Home > Web Front-end > JS Tutorial > Using native JavaScript to get the element style is just getting it_javascript skills

Using native JavaScript to get the element style is just getting it_javascript skills

WBOY
Release: 2016-05-16 16:34:42
Original
1100 people have browsed it

ps: It is to get the style, not to set the style. If no style value is set for the element, the default value given by the browser is returned. (Forum arrangement)

1. element.style: You can only get the style value written in the style attribute in the element tag. You cannot get the style value defined in and through Copy code The code is as follows:


var ele = document.getElementById('ele');
ele.style.color; //Get color

2. window.getComputedStyle(): You can get all the final CSS attribute values ​​​​of the current element.

Copy code The code is as follows:

window.getComputedStyle("element", "pseudo-class");

This method accepts two parameters: the element to get the calculated style from and a pseudo-element string (such as ":before"). If pseudo-element information is not required, the second parameter can be null. You can also use document.defaultView.getComputedStyle("element", "pseudo-class");

Copy code The code is as follows:

var ele = document.getElementById('ele');
var styles = window.getComputedStyle(ele,null);
styles.color; //Get color

You can view the number of browser default styles through style.length. IE6-8 does not support this method and you need to use the later method. For Firefox and Safari, the color will be converted to rgb format.

3. element.currentStyle: IE-specific, returns the final CSS attribute value currently applied to the element (including external link CSS files,