This article describes how to obtain element styles using native javascript. For more information, see the following abstract:
During the development process, we often encounter many methods to get or change the DOM element style through js, such as modifying the DOM element class. Now we will discuss how to use native js to obtain CSS styles of DOM elements. Note that obtaining is not set.
Before getting started, let's get all CSS attribute objects that are finally applied to the element. If no style is set for the element, the default style of the browser will also be returned.
1. ele. style
When learning DOM, we can see that the element style value is obtained through ele. style, but sometimes it is not the node style value, but the null value. This is because ele. style can only get the style values written in the style attribute in the element label, and the definition cannot be obtained inAnd pass Loaded style attributes
Example:
The code is as follows:
Var test = document. getElementById ("test ");
// Obtain the color of the node
Test. style. color;
2. getComputedStyle ()
GetComputedStyle is a CSS attribute value that can be used to obtain all the final CSS attribute values of the current element.
Syntax:
Window. getComputedStyle ("element", "Pseudo Class ");
This method accepts two parameters: the element to obtain the calculated style and a pseudo element string (for example, ": before "). If the pseudo element information is not required, the second parameter can be null. You can also use the document. defaultView. getComputedStyle ("element", "Pseudo Class ");
Example:
The code is as follows:
Var test = document. getElementById ("test "),
Demo = window. getComputedStyle (test, null );
// Obtain the color of the node
Demo. color
Note: Firefox and Safari convert colors to rgb format. if there are no styles on the test node, use style. length to view the number of default styles in the browser. IE6-8 does not support this method, you need to use the following method
3. ele. currentStyle
CurrentStyle is an attribute of IE browser. Its syntax is similar to ele. similar to style, the difference is that element. currentStyle returns the final CSS attribute value of the current element application (including the external link CSS file, embedded in the page