Home > Web Front-end > JS Tutorial > body text

Native javascript gets element style_javascript skills

WBOY
Release: 2016-05-16 16:22:34
Original
922 people have browsed it

Summary:
During the development process, we often encounter obtaining or changing the style of DOM elements through js. There are many methods, such as changing the class of DOM elements. Now we discuss native js to get the CSS style of DOM elements. Note that it is getting and not setting

Before we start, let’s talk about the meaning of getting all CSS attribute objects that are finally applied to the element. If no style is set for the element, the browser’s default style will also be returned.

1.ele.style
When I was learning DOM, I saw that the element style value was obtained through ele.style, but sometimes what was obtained was not the style value of the node, but a null value. This is because ele.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

Example:

Copy code The code is as follows:

         var test = document.getElementById("test");
//Get the color of the node
         test.style.color;

2. getComputedStyle()
GetComputedStyle is a method that can get all the final CSS attribute values ​​​​of the current element.

The syntax is as follows:

window.getComputedStyle("Element", "Pseudo-class");

This method accepts two parameters: the element to obtain the calculated style 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");

Example:

Copy code The code is as follows:

         var test = document.getElementById("test"),
          demo = window.getComputedStyle(test, null);
//Get the color of the node
demo.color

Note: Firefox and Safari will convert the color into rgb format. If there is no style on the test node, use style.length to check the number of browser default styles. IE6-8 does not support this method, you need to use the following method

3. ele.currentStyle
currentStyle is an attribute of IE browser itself. Its syntax is similar to ele.style. The difference is that element.currentStyle returns the final CSS attribute value currently applied to the element (including external link CSS files and the