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. element.style: Only the style value written in the style attribute in the element tag cannot be obtained. The style attribute defined in <style></style> and loaded through <link href="css.css"> cannot be obtained.
The code copy is as follows:
var ele = document.getElementById('ele');
ele.style.color; //Get color
2. window.getComputedStyle(): It can obtain all the final CSS attribute values of the current element.
The code copy is as follows: window.getComputedStyle("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 via document.defaultView.getComputedStyle("element", "pseudo-class");
The code copy is as follows:
var ele = document.getElementById('ele');
var styles = window.getComputedStyle(ele,null);
styles.color; //Get color
You can use style.length to 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. element.currentStyle: Special for IE, it returns the final CSS attribute value of the element currently applied (including external link CSS file, <style> attribute embedded in the page, etc.).
The code copy is as follows:
var ele = document.getElementById('ele');
var styles = ele.currentStyle;
styles.color;
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 property name of the CSS style
The code copy is as follows:
var ele = document.getElementById('ele');
window.getComputedStyle(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 the camel format of the property name
The code copy is as follows:
var test = document.getElementById('test');
window.getComputedStyle(test, null).getPropertyValue("backgroundColor");
Note: This method only supports IE6-8.
The following style obtaining method is compatible with IE, chrome, FireFox, etc.
The code copy is as follows:
function getStyle(ele) {
var style = null;
if(window.getComputedStyle) {
style = window.getComputedStyle(ele, null);
}else{
style = ele.currentStyle;
}
return style;
}
In JQuery, css() is commonly used to obtain style properties, and its underlying operation applies the getComputedStyle and getPropertyValue methods.