Getting the element style with native JavaScript is just getting
- 2020-03-30 04:02:12
- 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. Element. style: can only get the style value written in the style attribute of the element tag, and 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
2, window.getcomputedstyle (): you can get all the final used CSS attribute values of the current element.
window.getComputedStyle(" The element ", " pseudo-classes ");
This method takes two arguments: the element to get the computed style and a pseudo-element string (for example, ":before"). The second parameter can be null if the pseudo-element information is not required. Can also through the document. The defaultView. GetComputedStyle (" element ", "false"); To use the
3. Element.currentstyle :IE special, which returns the final CSS attribute value of the element currently applied (including the outer linked 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
4. GetPropertyValue () : gets the name of the direct property of the CSS style
5. GetAttribute () : similar to getPropertyValue, one difference is the camel's hump format of the attribute name
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.