js和css中WEB元素的距离和宽度高度等问题

网页元素的宽高度 以及距边界的距离问题一直困扰着很多人,虽然网上有很多文章,但是基本都不兼容各种浏览器或者是没讲清楚,把外文解释不加思考的翻译过来。 下面有个获取元素据上下左右边界的位置的函数很有用

index.html

网页可见区域宽:document.body.clientWidth
网页可见区域高:document.body.clientHeight
网页可见区域宽:document.body.offsetWidth (包括边线的宽)
网页可见区域高:document.body.offsetHeight (包括边线的宽)
网页正文全文宽:document.body.scrollWidth
网页正文全文高:document.body.scrollHeight
网页被卷去的高:document.body.scrollTop
网页被卷去的左:document.body.scrollLeft

HTML精确定位:clientWidth:
scrollHeight: 获取对象的滚动高度。
scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离
scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离
scrollWidth:获取对象的滚动宽度
obj.offsetHeight: 指obj控件自身的绝对高度
obj.offsetWidth: 指obj控件自身的绝对宽度
offsetLeft:获取对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置
offsetTop:获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置
document.div.scrollTop 垂直方向滚动的值
event.clientX + document.div.scrollTop 相对文档的水平座标+垂直方向滚动的量

IE,FireFox 差异如下:
IE6.0、FF1.06+:
clientWidth = width + padding
clientHeight = height + padding
offsetWidth = width + padding + border
offsetHeight = height + padding + border
-->
<script type="text/javascript">
//设置DIV的位置
function setOffsets()
{
var popup = document.getElementById('popup');
var inputv = document.getElementById('inputObj');

var width = inputv.offsetWidth;
var left = getOffsetLeft(inputv);
var top = getOffsetTop(inputv) + inputv.offsetHeight;

popup.style.border = '1px solid lightblue';//悬浮DIV popup
popup.style.width = width + "px";
popup.style.left = left + "px";
popup.style.top = top + "px";

popup.style.height = "100px";
}
//距离左边的距离
function getOffsetLeft(field)
{
return getOffset(field,"offsetLeft");
}
//距离顶部的距离
function getOffsetTop(field)
{
return getOffset(field,"offsetTop");
}
//循环结点得到相对距离
function getOffset(field,attr)
{
var offset = 0;
while(field)
{
offset += field[attr];
field = field.offsetParent;
}
return offset;
}
</script>