clientWidth、offsetWidth、clientHeight、offsetHeight的测试比较

阅读更多

转摘

IE6.0、FF1.06+:
clientWidth = width + padding
clientHeight = height + padding
offsetWidth = width + padding + border
offsetHeight = height + padding + border
IE5.0/5.5:
clientWidth = width - border
clientHeight = height - border
offsetWidth = width
offsetHeight = height
(需要提一下:CSS中的margin属性,与clientWidth、offsetWidth、clientHeight、offsetHeight均无关)

具体效果请参见下面的代码:

js 代码
  1. "-//W3C//DTD XHTML 1.0 Transitional//EN" "[url=http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd[/url]">   
  2. "[url=http://www.w3.org/1999/xhtml]http://www.w3.org/1999/xhtml[/url]" lang="gb2312">   
  3.   
  4.   
  5.  代码实例:关于clientWidth、offsetWidth、clientHeight、offsetHeight的测试比较    
  6. "content-type" content="text/html; charset=gb2312" />   
  7. "author" content="枫岩,[email protected]">   
  8. "copyright" content="[url=http://www.cnlei.com]http://www.cnlei.com[/url]" />   
  9. "description" content="关于clientWidth、offsetWidth、clientHeight、offsetHeight的测试比较" />   
  10. "text/css" media="all">   
  11. body {font-size:14px;}   
  12. a,a:visited {color:#00f;}  
  13. #Div_CnLei {   
  14. width:300px;   
  15. height:200px;   
  16. padding:10px;   
  17. border:10px solid #ccc;   
  18. background:#eee;   
  19. font-size:12px;   
  20. }  
  21. #Div_CnLei p {margin:0;padding:10px;background:#fff;}   
  22.   
  23. "text/javascript">   
  24. function Obj(s){   
  25. return document.getElementById(s)?document.getElementById(s):s;   
  26. }   
  27. function GetClientWidth(o){   
  28. return Obj(o).clientWidth;   
  29. }   
  30. function GetClientHeight(o){   
  31. return Obj(o).clientHeight;   
  32. }   
  33. function GetOffsetWidth(o){   
  34. return Obj(o).offsetWidth;   
  35. }   
  36. function GetOffsetHeight(o){   
  37. return Obj(o).offsetHeight;   
  38. }   
  39.   
  40.   
  41.   
  42. 点击下面的链接:

      
  43. "Div_CnLei">   
  44. "javascript:alert(GetClientWidth('Div_CnLei'));">GetClientWidth();  "javascript:alert(GetClientHeight('Div_CnLei'));">GetClientHeight();

      
  45. "javascript:alert(GetOffsetWidth('Div_CnLei'));">GetOffsetWidth();  "javascript:alert(GetOffsetHeight('Div_CnLei'));">GetOffsetHeight();

      
  
  • "Description">   
  • IE6.0、FF1.06+:   

  • clientWidth = width + padding = 300+10×2 = 320   
  • clientHeight = height + padding = 200+10×2 = 220   
  • offsetWidth = width + padding + border = 300+10×2+10×2= 340   
  • offsetHeight = height + padding + border = 200+10×2+10×2 = 240

      
  • IE5.0/5.5:   

  • clientWidth = width - border = 300-10×2 = 280   
  • clientHeight = height - border = 200-10×2 = 180   
  • offsetWidth = width = 300   
  • offsetHeight = height = 200

      
  •   
  •   
  •   
  • 你可能感兴趣的:(JavaScript,CSS,XHTML,Gmail,HTML)