To get a style attribute for an element, you can use:
1 < ID= "DIV01" style= "color:red">123</Div >23var ele = document.getElementById ("div01"); 4 Console.log (Ele.style.color);
However, this can only get the inline style that is written on the element, which is not available for link's style file or the style written in <style></style>.
The standard browser provides a getComputedStyle function that uses:
1 // The first parameter is the node to get the style, the second parameter is a pseudo-class, such as: hover, or null if not. Returns the Cssstyledeclaration object; 2 window.getComputedStyle (element, Pseudo-Class) 3 4 // The desired style can be obtained by the property name, and the font color of the element is given below 5 window.getComputedStyle (Ele,false) ["Color"];
IE is not supported, but it provides a Currentstyle object that results in the same getcomputedstyle as the
1 // The font color of the element can also be obtained by IE in this way 2 ele.currentstyle["Color"];
Combined with the above situation, we can be compatible to get a reliable solution!
1 function GetStyle (ele,name) { 2 if (ele.currentstyle) {// IE processing 3 return Ele.currentstyle[name]; 4 } else { // Standard browser handling 5 false ) [name]; 6 } }
It is convenient to get the DIV01 style again!
The complete code is as follows:
1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4 <MetaCharSet= "UTF-8">5 <title>Demo</title>6 <style>7 #div01{font-size:16px;}8 </style>9 </Head>Ten <Body> One <DivID= "Div01"style= "Color:red">123</Div> A <Script> - functionGetStyle (ele,name) { - if(ele.currentstyle) { the returnEle.currentstyle[name]; - } Else { - returngetComputedStyle (Ele,false) [name]; - } + } - + varEle=document.getElementById ("DIV01"); A at Console.log (GetStyle (Ele,"Color")); //RGB (255, 0, 0) - Console.log (GetStyle (Ele,"fontSize")); //16px - - </Script> - </Body> - </HTML>
Compatible get-style function GetStyle ()