详解javascript中offsetTop/Left、offsetWidth/Height、clientWidth/clientHeight

来源:互联网 发布:网络歌手虞姬资料 编辑:程序博客网 时间:2024/05/23 07:24

javascript中获取元素的尺寸位置等,有好多个属性(clientWidth,clientHeight,offsetWidth,offsetHeight,scrollWidth,scrollHeight)等,本文主要介绍各自属性的意义。




一、对于获取div尺寸

clientWidth = width + paddingclientHeight = height + paddingoffsetWidth = width + padding + borderoffsetHeight = height + padding + border

二、对于获取整个网页尺寸

网页可见区域宽: document.body.clientWidth
网页可见区域高: document.body.clientHeight
网页可见区域宽: document.body.offsetWidth (包括边线的宽IE8,chrome中=clientWidth)
网页可见区域高: document.body.offsetHeight (包括边线的高IE8,chrome中=scrollHeight)
网页正文全文宽: document.body.scrollWidth
网页正文全文高: document.body.scrollHeight
屏幕分辨率的高: window.screen.height
屏幕分辨率的宽: window.screen.width
屏幕可用工作区高度: window.screen.availHeight
屏幕可用工作区宽度: window.screen.availWidth

三、测试例子

<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><style type="text/css">body{border: 10px solid orange;margin: 0;}#div1 {width: 300px;height: 200px;border:20px solid #ccc;padding: 50px;margin:20px;background: #0cc;}</style><script type="text/javascript">function getBodySize() {var ta1 = document.getElementById("ta1");ta1.value="网页可见区域宽:"+document.documentElement.clientWidth+"\n"+"网页可见区域高:"+document.documentElement.clientHeight+"\n"+"网页可见区域宽(包括边线的宽IE8,chome中=clientWidth):"+document.documentElement.offsetWidth+"\n"+"网页可见区域高(包括scroll未显示的宽=scrollHeight):"+document.documentElement.offsetHeight+ "\n网页正文全文宽:"+document.body.scrollWidth+"\n"+"网页正文全文高:"+document.body.scrollHeight+"\n"+"网页被卷去的高:"+document.body.scrollTop+"\n"+"网页被卷去的左:"+document.body.scrollLeft;}function getDivSize() {var div1 = document.getElementById('div1');var ta1 = document.getElementById("ta1");var str = "clientWidth = width + padding=300+50+50="+div1.clientWidth;str = str +"\nclientHeight = height + padding=200+50+50="+div1.clientHeight;str = str +"\noffsetWidth = width + padding + border=300+50+50+20+20="+div1.offsetWidth;str = str +"\noffsetHeight = height + padding + border=200+50+50+20+20="+div1.offsetHeight;str = str +"\noffsetTop = 获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置="+div1.offsetTop;str = str +"\noffsetLeft = 获取对象相对于版面或由 offsetLeft 属性指定的父坐标的计算左端位置="+div1.offsetLeft;ta1.value = str;//alert(div1.clientWidth + ',' + div1.clientHeight);//alert(div1.offsetWidth + ',' + div1.offsetHeight);//alert(div1.offsetTop + ',' + div1.offsetLeft);}</script></head><body><div id="div1"></div><textarea id="ta1" rows="15" cols="100" style="margin-left: 30px;">在w3school,你可以找到你所需要的所有的网站建设教程。</textarea><br/><input type="button" value="获取div尺寸" onclick="getDivSize();"><input type="button" value="获取body尺寸" onclick="getBodySize();"><br><script type="text/javascript">for (var i = 1;i <= 100;i ++) {document.write('<br>' + i);}</script></body></html>

结果截图:


0 0
原创粉丝点击