In practical applications, Retrieving Element styles is often used in practical applications. For pure html, elem is used directly. style. attr can be obtained, but more often we need to get the final style attribute of the element from Css. therefore, we need to use currentStyle of IE and getPropertyValue of W3C to obtain it.
Elem. style. the method for retrieving styles by attr is not mentioned. first, let's look at the currentStyle method. This object exclusive to ie represents the object format and style specified in the global style sheet, embedded style, and HTML tag attributes. in IE, you can get the Css attribute value of the element.
For other standard browsers, W3C also provides the getPropertyValue method, which is a little complicated. First, you must use document. defaultView. getComputedStyle gets the Css style object, and then obtains the attribute value through getPropertyValue of the object.
The two methods are the same in IE and W3C. they obtain the final value of the element Css attribute, which is the same as that of Css.
The difference is that the IE method is obtained by the camper name (such as textAlign) of the Css attribute, while the W3C method is obtained by the original attribute name (such as text-align) of the element Css) therefore, when using the W3C method, you need to make a simple process for the Css attribute name.
Based on this, we can encapsulate a method to obtain the element property value, as follows:
The Code is as follows:
Function attrStyle (elem, attr ){
If (elem. attr ){
// If the style exists in html, get it first
Return elem. style [attr];
} Else if (elem. currentStyle ){
// Obtain the final CSS attribute style under IE (equivalent to CSS priority)
Return elem. currentStyle [attr];
} Else if (document. defaultView & document. defaultView. getComputedStyle ){
// The W3C standard method to obtain the final CSS attribute style (equivalent to the CSS priority)
// Note that this method is obtained from the original format (text-align), so you need to convert it.
Attr = attr. replace (/([A-Z])/g, '-$ 1'). toLowerCase ();
// Get the style object and get the attribute value
Return document. defaultView. getComputedStyle (elem, null). getPropertyValue (attr );
} Else {
Return null;
}
}
Remember to be proficient in the section on getting element positions in the JavaScript book (forgot chapter 6th or chapter 7th) and have a more detailed explanation on getting element style attribute values. first known document. defaultVies. getComputedStyle is from this book. A great book. If you are interested, you must read it.
Mr Think's blog: http://mrthink.net/js-get-cssproperty/