Home > Web Front-end > JS Tutorial > Summary of native methods for obtaining styles in JavaScript_javascript tips

Summary of native methods for obtaining styles in JavaScript_javascript tips

WBOY
Release: 2016-05-16 16:34:54
Original
1064 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: can only obtain the style value written in the style attribute in the element tag, and cannot obtain the style value defined in and through Loaded style attributes

Copy code The code is as follows:

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

2. window.getComputedStyle(): 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 the 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,