document.body 和 document.documentElement 的区别

在设计页面时可能经常会用到固定层的位置,这就需要获取一些html对象的坐标以更灵活的设置目标层的坐标,这里可能就会用到document.body.scrollTop等属性,但是此属性在xhtml标准网页或者更简单的说是带标签的页面里得到的结果是0,如果不要此标签则一切正常,那么在xhtml页面怎么获得body的坐标呢,当然有办法-使用document.documentElement来取代document.body,可以这样写,例:
var top = document.documentElement.scrollTop || document.body.scrollTop;
      在javascript里||是个好东西,除了能用在if等条件判断里,还能用在变量赋值上。那么上例等同于下例。
例:
var top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
这么写可以得到很好的兼容性。

       相反,如果不做声明的话,document.documentElement.scrollTop反而会显示为0。

      顺便再存一下这个图吧,总是挺难记清楚:

document.body 和 document.documentElement 的区别_第1张图片

以上内容转载地址:http://www.cnblogs.com/scy251147/archive/2011/04/10/2011420.html

另外一些基础知识:

document.body和document.documentElement比较:

     document.body是DOM中Document对象里的body节点, document.documentElement是文档对象根节点(html)的引用。
     IE在怪异模型(quick mode)下document.documentElement无法正确取到clietHeight scrollHeight等值,比如clietHeight=0。可以见IE的怪异模型并没有把html作为盒子模型的一部分,好在现在很少使用怪异模型。(注:如果页面没写DTD或写的不对,IE6默认使用怪异模型解析页面)

document.body.scrollHeight和document.documentElement.scrollHeight的区别:

     document.body.scrollHeight是body元素的滚动高度,document.documentElement.scrollHeight为页面的滚动高度,且 document.documentElement.scrollHeight在IE和Firefox下还有点小差异。
     IE : document.documentElement.scrollHeight = document.body.scrollHeight + marginTop bottom高度 + 上下border宽度
     firefox : document.documentElement.scrollHeight = document.body.scrollHeight + marginTop bottom高度

注意:要获取当前页面的滚动条纵坐标位置:

document .documentElement.scrollTop;
而不是: 
document .body.scrollTop; 
documentElement 对应的是 html 标签,而 body 对应的是 body 标签。

各个属性如下:


网页可见区域宽: document .body.clientWidth;
网页可见区域高: document .body.clientHeight;

网页可见区域宽: document .body.offsetWidth   (包括边线的宽);
网页可见区域高: document .body.offsetHeight (包括边线的宽);

网页正文全文宽: document .body.scrollWidth;
网页正文全文高: document .body.scrollHeight;

网页被卷去的高: document .body.scrollTop;
网页被卷去的左: document .body.scrollLeft;

网页正文部分上: window.screenTop;
网页正文部分左: window.screenLeft;

屏幕分辨率的高: window.screen.height;
屏幕分辨率的宽: window.screen.width;
屏幕可用工作区高度: window.screen.availHeight;
屏幕可用工作区宽度:window.screen.availWidth; 
scrollHeight: 获取对象的滚动高度。  
scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离
scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离
scrollWidth:获取对象的滚动宽度

offsetHeight:获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的高度
offsetLeft:获取对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置
offsetTop:获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置  

event.clientX 相对文档的水平座标
event.clientY 相对文档的垂直座标
event.offsetX 相对容器的水平坐标
event.offsetY 相对容器的垂直坐标
  
document .documentElement.scrollTop 垂直方向滚动的值
event.clientX+document .documentElement.scrollTop 相对文档的水平座标+垂直方向滚动的量 









你可能感兴趣的:(web)