SoFunction
Updated on 2025-03-03

Summary of native methods for getting styles in JavaScript

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 sorted)

1、:Only the style value written in the style attribute in the element tag cannot be obtained, and the style attribute defined in <style></style> and loaded through <link href=""> cannot be obtained.

Copy the codeThe code is as follows:

var ele = ('ele');
;     //Get the color

2、():All the end-used CSS attribute values ​​of the current element can be obtained.

Copy the codeThe code is as follows:
("element", "pseudo-class");

This method accepts two parameters: to get the element of the computed style and a pseudo-element string (for example ":before"). If pseudo-element information is not required, the second parameter can be null. It can also be used by ("element", "pseudo-class");
Copy the codeThe code is as follows:

var ele = ('ele');
var styles = (ele,null);
;  //Get the color

You can view the number of browser default styles. IE6-8 does not support this method, and the following method needs to be used. For Firefox and Safari, the color will be converted to rgb format.

3、:IE is dedicated, which returns the final CSS attribute value of the element currently applied (including external link CSS files, <style> attributes embedded in the page, etc.).

Copy the codeThe code is as follows:

var ele = ('ele');
var styles = ;
;

Note: For comprehensive attribute border, etc., ie returns undefined. Some other browsers return values, and some do not return, but attributes like borderLeftWidth return values.

4、getPropertyValue():Get the direct attribute name of the CSS style

Copy the codeThe code is as follows:

var ele = ('ele');
(ele,null).getPropertyValue('color');

Note: The attribute name does not support camel format, IE6-8 does not support this method, so the following method is required

5、getAttribute():Similar to getPropertyValue, one difference is that the property name camel format

Copy the codeThe code is as follows:

var test = ('test');
(test, null).getPropertyValue("backgroundColor");

Note: This method only supports IE6-8.

The following style obtaining method is compatible with IE, chrome, FireFox, etc.

Copy the codeThe code is as follows:

function getStyle(ele) {
     var style = null;
    
    if() {
         style = (ele, null);
     }else{
         style = ;
     }
    
    return style;
}

In JQuery, css() is commonly used to obtain style properties, and its underlying operation applies the getComputedStyle and getPropertyValue methods.