offsetTop/offsetHeight scrollTop/scrollHeight 的区别

offsetTop/offsetHeight   scrollTop/scrollHeight  这几个属性困扰了我N久,这次一定要搞定。

 

假设 obj 为某个 HTML 控件。

obj.offsetTop   obj距离上方或上层控件的位置,整型,单位像素。

obj.offsetHeight   obj自身的高度,整型,单位像素。

 

offsetTop 可以获得 HTML 元素距离上方或外层元素的位置,style.top 也是可以的,二者的区别是:

一、offsetTop 返回的是数字,而 style.top 返回的是字符串,除了数字外还带有单位:px。
二、offsetTop 只读,而 style.top 可读写。
三、如果没有给 HTML 元素指定过 top 样式,则 style.top 返回的是空字符串。

 

scrollTop 是“卷”起来的高度值,示例:
<div style="width:100px;height:100px;overflow:hidden;" id="p">
    <div style="width:50px;height:300px;" id="t">如果为 p 设置了 scrollTop,这些内容可能不会完全显示。</div>
</div>
<script type="text/javascript">
    var p = document.getElementById("p");
    p.scrollTop = 10;
</script>
由于为外层元素 p 设置了 scrollTop,所以内层元素会向上卷。

 

scrollHeight 与 offsetHeight

offsetHeight是自身元素的高度,scrollHeight是 自身元素的高度+隐藏元素的高度(是不是可以理解成内层元素的offsetHeight值???)。

<div id="container" style=" width:100px; height:100px; overflow:auto;">

    <p style=" height:250px; ">
    别再做情人 做只猫 做只狗 不做情人 做只宠物至少可爱迷人 和你相交不浅无谓明日会被你憎
    </p>
</div>
<script>
    alert(document.getElementById("container").offsetHeight);
    alert(document.getElementById("container").scrollHeight);
</script>

将依次输出100,250。因为已经指定了元素的height为100px,所以offsetHeight始终为100px;内部元素为 250px,而容器元素只有100px,那么还有150px的内容它无法显示出来,但它却是实际存在的,所以scrollHeight值为 100+150=250。

转:http://hi.baidu.com/lampers/item/1605adc13daa00350931c6fc

http://www.cnblogs.com/fullhouse/archive/2012/01/16/2324131.html

 

            alert("网页可见区域宽:" + 'document.body.clientWidth.'+document.body.clientWidth);
            alert("网页可见区域高:" + 'document.body.clientHeight.'+document.body.clientHeight);
            alert("网页可见区域高 (包括边线的宽):" + 'document.body.offsetWidth.'+document.body.offsetWidth);
            alert("网页可见区域高 (包括边线的高):" + 'document.body.offsetHeight.'+document.body.offsetHeight);
            alert("网页正文全文宽:" + 'document.body.scrollWidth.'+document.body.scrollWidth);
            alert("网页正文全文高:" + 'document.body.scrollHeight.'+document.body.scrollHeight);
            alert("网页被卷去的高:" + 'document.body.scrollTop.'+document.body.scrollTop);
            alert("网页被卷去的左:" + 'document.body.scrollLeft.'+document.body.scrollLeft);
            alert("网页正文部分上:" + "window.screenTop."+window.screenTop);
            alert("网页正文部分左:" + "window.screenLeft."+window.screenLeft);
            alert("屏幕分辨率的高:" + "window.screen.height."+window.screen.height);
            alert("屏幕分辨率的宽:" + "window.screen.width."+window.screen.width);
            alert("屏幕可用工作区高度:" + "window.screen.availHeight."+window.screen.availHeight);
            alert("屏幕可用工作区宽度:" +  "window.screen.availWidth." +window.screen.availWidth);
View Code

 

posted @ 2015-04-24 10:27  范小武  阅读(3056)  评论(0编辑  收藏  举报