JS get element width
1. Use inline styles to directly write CSS in the style attribute of HTML elements.
<Div id = "d1" style = "width: 100px; Height: 200px;"> </div>
Copy the code and use the following JS Code to obtain attributes such as width,
Alert (document. getelementbyid ('d1 '). style. width); // 100px
The width and height of the copied code can be obtained in Firefox, ie, opera, Safari, and chrome.
2. Embed, link, or introduce a style sheet (non-inline style). In this case, you cannot obtain it through element. style. width.
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> B .html </title>
<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "Description" content = "this is my page">
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Style type = "text/CSS">
# D2 {
Width: 400px;
Height: 200px;
Border: 5px solid gray;
Padding: 5px;
}
</Style>
<SCRIPT>
Window. onload = function (){
2. Embed, link, or introduce a style sheet (non-inline style)
// Ie: Use currentstyle
Alert (document. getelementbyid ('d2 '). currentstyle. width); // 400px IE
// Ff, Safari, opera, chrome: Use window. getcomputedstyle
VaR El = Document. getelementbyid ('d2 ');
Alert (window. getcomputedstyle (El, null). style. width); // 400px safari, opera, chrome
}
</SCRIPT>
</Head>
<Body>
<Div id = "D2"> </div>
</Body>
</Html>
Finally encapsulated in a method,
Function getrealstyle (El, cssname)
{
VaR Len = arguments. length, sty, F, FV;
'Currentstyle' in El? Sty = El. currentstyle: 'getcomputedstyle' in window? Sty = Window. getcomputedstyle (El, null): NULL;
If (cssname = "opacity" & document. All ){
F = El. filters;
F & F. length> 0 & F. Alpha? FV = f. Alpha. Opacity/100: FV = 1;
Return FV;
}
Cssname = "float "? Document. All? Cssname = 'stylefloat': cssname = 'cssfloat': cssname;
Sty = (LEN = 2 )? Sty [cssname]: sty;
Return sty;
}
If you only want to get the style object of the element, pass the first parameter, and the second parameter is to get the value of the style attribute of this object as styname.