现在的位置: 首页 > 综合 > 正文

困扰我的那些scrollTop,offsetwidth等等关于位置的属性

2013年04月28日 ⁄ 综合 ⁄ 共 2637字 ⁄ 字号 评论关闭

网页可见区域宽: document.body.clientWidth;
网页可见区域高: document.body.clientHeight;
网页可见区域宽: document.body.offsetWidth   (包括边线的宽);
网页可见区域高: document.body.offsetHeight  (包括边线的宽);
网页正文全文宽: document.body.scrollWidth;
网页正文全文高: document.body.scrollHeight;
网页被卷去的高: document.body.scrollTop; 在ie5之后不用它了。应该用document.documentElement.scrollTop;
网页被卷去的左: document.body.scrollLeft;

 

网页正文部分上: window.screenTop;
网页正文部分左: window.screenLeft;
屏幕分辨率的高: window.screen.height;
屏幕分辨率的宽: window.screen.width;
屏幕可用工作区高度: window.screen.availHeight;
屏幕可用工作区宽度:window.screen.availWidth;

offsetTop 指元素距离上方或上层控件的位置,整型,单位像素。
offsetLeft 指元素距离左方或上层控件的位置,整型,单位像素。
offsetWidth 指元素控件自身的宽度,整型,单位像素。
offsetHeight 指元素控件自身的高度,整型,单位像素。

 

关于top、clientTop、scrollTop、offsetTop" name=image_operate_73661292071092531 alt="Js 关于top、clientTop、scrollTop、offsetTop" src="http://s5.sinaimg.cn/middle/461c24d5g9721be6f9b44&690" width=609 height=602>

这里说说四种浏览器对 document.body 的 clientHeight、offsetHeight 和 scrollHeight 的解释。

这四种浏览器分别为IE(Internet Explorer)、NS(Netscape)、Opera、FF(FireFox)。

clientHeight

四种浏览器对 clientHeight 的解释都没有什么异议,都认为是内容可视区域的高度,也就是说页面浏览器中可以看到内容的这个区域的高度,一般是最后一个工具条以下到状态栏以上的这个区域,与页面内容无关。

offsetHeight

IE、Opera 认为 offsetHeight = clientHeight + 滚动条 + 边框。
NS、FF 认为 offsetHeight 是网页内容实际高度,可以小于 clientHeight。

scrollHeight

IE、Opera 认为 scrollHeight 是网页内容实际高度,可以小于 clientHeight。
NS、FF 认为 scrollHeight 是网页内容高度,不过最小值是 clientHeight。

简单地说

clientHeight 就是透过浏览器看内容的这个区域高度。
NS、 FF 认为 offsetHeight 和 scrollHeight 都是网页内容高度,只不过当网页内容高度小于等于 clientHeight 时,scrollHeight 的值是 clientHeight,而 offsetHeight 可以小于 clientHeight。
IE、Opera 认为 offsetHeight 是可视区域 clientHeight 滚动条加边框。scrollHeight 则是网页内容实际高度。

同理

clientWidth、offsetWidth 和 scrollWidth 的解释与上面相同,只是把高度换成宽度即可。

以上主要指IE之中,FireFox差异如下:
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均无关)

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

document.documentElement.scrollTop;

而不是:

document.body.scrollTop;

documentElement 对应的是 html 标签,而 body 对应的是 body 标签。

在标准w3c下,document.body.scrollTop恒为0,需要用document.documentElement.scrollTop来代替

如果你想定位鼠标相对于页面的绝对位置时,你会发现google里面1000篇文章里面有999.99篇会让你使用event.clientX+document.body.scrollLeft,event.clientY+document.body.scrollTop,如果你发现你的鼠标定位偏离了你的想象,请不要奇怪,这是再正常不过的事情。
ie5.5之后已经不支持document.body.scrollX对象了。
所以在编程的时候,请加上这样的判断
if (document.body && document.body.scrollTop && document.body.scrollLeft)
{
top=document.body.scrollTop;
left=document.body.scrollleft;   
}
if (document.documentElement && document.documentElement.scrollTop && document.documentElement.scrollLeft)
{
top=document.documentElement.scrollTop;
left=document.documentElement.scrollLeft;

抱歉!评论已关闭.