Offsetwidth/offsetheight method of getting elements from Web page effects
The idea is simple: get the offsetwidth/offsetheight of the element, minus the padding and border of the element
element to set the Width/height by introducing a style sheet
There are two ways to introduce style sheets, one is to introduce a separate CSS tutorial file with the link tag, and the other is to use the style tag directly in the HTML page. Here's a second way of testing
<style>
div {width:100px}
</style>
<div>test<div>
<script>
function GetStyle (el, name) {
if (window.getComputedStyle) {
Return window.getComputedStyle (EL, null);
}else{
return el.currentstyle;
}
}
var div = document.getelementsbytagname (' div ') [0];
Alert (GetStyle (Div, ' width '));
</script>
100px is ejected from all browsers. Explains that the getComputedStyle and currentstyle can be used to get the width and height of the elements defined in the style sheet.
What if the element is not set wide in the style attribute, nor is it set wide in the style sheet, can you get it with getComputedStyle or currentstyle? The answer is getComputedStyle can, currentstyle not. As follows
<div>test<div>
<script>
function GetStyle (el, name) {
if (window.getComputedStyle) {
Return window.getComputedStyle (EL, null);
}else{
return el.currentstyle;
}
}
var div = document.getelementsbytagname (' div ') [0];
Alert (GetStyle (Div, ' width '));
</script>
Div has neither set the Style property nor introduced a style sheet. Firefox/ie9/safari/chrome/opera can be obtained in the wide-height (browser default), but not in the IE6/7/8, the return is auto.
Note that the GetStyle method takes precedence over getComputedStyle, and IE9 has supported the method. Therefore, the IE9 can be gained in width and height. But IE6/7/8 not supported, only use Currentstyle to get
<div>test<div>
<script>
function getstyle (EL) {
if ( window.getComputedStyle) {
return window.getcomputedstyle (el, null);
}else{
return El.currentstyle;
}
}
function Getwh (el, name) {
var val = name = = "width"? el.offsetWidth:el.offsetHeight,
& Nbsp; which = Name = = "width"? [' Left ', ' right ']: [' top ', ' bottom '];
//display is None
if (val = = 0) {
return 0;
& nbsp; .}
for (var i = 0, A; a = which[i++];) {
val-= parsefloat (GetStyle (el, "border" + A + "Width") | | 0;
val-= parsefloat (GetStyle (el, "padding" + a)) | | 0;
}
return val + ' px ';
}
var div = document.getelementsbytagname (' div ') [0];< br> alert (Getwh (Div, ' width '));
</script>