html - Width of an element accounting for quirks mode in javascript? -
i've been scanning through popular js libraries, can't find 1 has width function dom element accounts quirks mode in internet explorer. issue padding , borders don't counted in the width when quirks mode engaged. far can tell happens when doctype left out or doctype set html 3.2.
obviously set doctype standards compliant, script can embedded anywhere don't have control on doctype.
to break problem down smaller parts:
1) how detect quirks mode? 2) what's best way extract border , padding element compensate?
example prototype:
<html> <head> </head> <body> <div id="mydiv" style="width: 250px; pading-left: 1px; border: 2px black solid">hello</div> <script> alert($('mydiv').getwidth()) </script> </body> </html>
result:
253 (ff) 250 (ie)
thanks in advance!
@1
document.compatmode
"css1compat" means "standards mode" , "backcompat" means "quirks mode".
@2
offsetwidth property of html elements gives width on screen, in pixels.
<div id="mydiv" style="width: 250px; padding-left: 1px; border: 2px black solid">hello</div> document.getelementbyid('mydiv').offsetwidth //255 (standards) 250 (quirks)
a function compensates width ie quirksmode has check rendering mode add borders , padding width;
function compensatewidth( el, targetwidth ){ var removeunit = function( str ){ if( str.indexof('px') ){ return str.replace('px','') * 1; } else { //because won't work other units... 1 may wish implement return 0; } } if(document.compatmode && document.compatmode=="backcompat"){ if(targetwidth && el.offsetwidth < targetwidth){ el.style.width = targetwidth; } else if (el.currentstyle){ var borders = removeunit(el.currentstyle['borderleftwidth']) + removeunit(el.currentstyle['borderrightwidth']); var paddings = removeunit(el.currentstyle['paddingleft']) + removeunit(el.currentstyle['paddingright']); el.style.width = el.offsetwidth + borders + paddings +'px'; } } }
now there 2 ways use it:
var div = document.getelementbyid('mydiv') // try calculate target width, won't able work units other px compensatewidth( div ); //if know width should in standards mode compensatewidth( div, 254 );
Comments
Post a Comment