天天看点

document.body和document.documentElement - [js]

http://www.blueidea.com/tech/site/2006/3130.asp

在一般普通页面(无DTD格式声明),document.body各个属性说明:

  • scrollHeight:  内容实际高度
  • scrollWidth: 内容实际宽度
  • clientHeight: 可见区域高度
  • clientWidth: 可见区域宽度
  • offsetHeight: 包括边线和滚动条的高度
  • OffsetWidth: 包括边线和滚动条的宽度
  • window.scrollTop, window.scrollLeft: 滚动条离最上端、左端的距离
  • window.screen.height,window.screen.width: 分辨率高度、宽度

   在有DTD格式声明的情况下,即页面中有<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">,document.body各个属性的说明如下:

  • scrollHeight, clientHeight, offsetHeight:  内容实际高度
  • scrollWidth, clientWidth, offsetWidth: 页面可视部分宽度
  • scrollTop: 一直为0

   这时候如果要得到页面的实际宽度,需要使用document.documentElement.clientWidth(xhtml标准)。而得到滚动条纵坐标位置,则需要使用document.documentElement.scrollTop。(在没有声明DTD的时候,这两个值反而都为0)

   documentElement对应的是html标签,而body对应的是body标签。IE在怪异模型(quick mode,也就是页面没有DTD或者写的不对)下,document.documentElement无法得到正确的clientHeight值,可能怪异模型没有把html作为盒子模型的一部分。在IE下可以通过获得document.compatMode的返回值判断是否为怪异模型:var height = document.compatMode=="CSS1Compat" ? document.documentElement.clientHeight : document.body.clientHeight; var height = document.compatMode=="BackCompat" ? document.body.clientHeight : document.documentElement.clientHeight;

   也就是说如果html中有DTD说明,那么得到各个属性最好是使用document.documentElement,而如果没有的话,使用document.body。