As we all know, document. getElementById ('element '). style. xxx can obtain the style information of an element, but it only obtains the style rules in the DOM element style attribute. For external style tables referenced by the class attribute, we cannot get the information we need.
In the DOM standard, there is a global method getComputedStyle, which can get the information of the current object style rules, such as getComputedStyle (obj, null). paddingLeft to get the left padding of the object. However, this method is not complete yet. The evil IE does not support this method. It has its own implementation method, namely currentStyle. Unlike the global method getComputedStyle, it exists as a DOM element attribute, for example, obj. currentStyle. paddingLeft: The left padding of the object is obtained in IE. The Compatibility Statement is as follows:
Copy codeThe Code is as follows:
Return window. getComputedStyle? Window. getComputedStyle (obj, null). paddingLeft: obj. currentStyle. paddingLeft;
In this way, the current style information of the object can be returned in IE and FF.
Note: To obtain the color information of the current object, IE returns the hexadecimal '# ffff', and FF returns the rgb (255,255,255)
You can use the style attribute of js to obtain the html Tag style, but cannot obtain the non-interline style. So how can I use js to obtain the css non-interline style? CurrentStyle can be used in IE, while getComputedStyle is required in Firefox. Below is a small example:
Copy codeThe Code is as follows:
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> js uses currentStyle and getComputedStyle to obtain css styles </title>
<Style type = "text/css">
# Div1 {width: 100px; height: 100px; background: red ;}
</Style>
<Script type = "text/javascript">
Function getStyle (obj, attr)
{
If (obj. currentStyle)
{
Return obj. currentStyle [attr];
}
Else
{
Return getComputedStyle (obj, false) [attr];
}
}
Window. onload = function ()
{
Var oDiv = document. getElementById ('div1 ');
Alert (getStyle (oDiv, 'width '))
}
</Script>
</Head>
<Body>
<Div id = "div1"> </div>
</Body>
</Html>