Summary of native methods for getting styles in JavaScript
- 2020-03-30 04:02:23
- OfStack
Ps: get style, not set style. If no style value is set for the element, the default value given by the browser is returned. (forum arrangement)
1, the element. Style: Can only get the style value written in the style attribute of the element tag, cannot get the style value defined in < Style> < / style> And through < The link href = "CSS. CSS >" The style properties loaded in
var ele = document.getElementById('ele');
ele.style.color; //Gets the color
3, element. CurrentStyle:
IE special, return is the element currently applied to the final CSS attribute value (including the outer chain CSS file, embedded in the page < Style> Properties, etc.).
var ele = document.getElementById('ele');
var styles = ele.currentStyle;
styles.color;
Note: for synthetic properties such as border, ie returns undefined, other browsers either return a value or not, but a property such as borderLeftWidth returns a value
The following get style methods are compatible with IE, chrome, FireFox, and more
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 get style properties, and its underlying operation applies getComputedStyle and getPropertyValue methods.