http://www.css88.com/archives/1772
以前绝大多数的使用下面的代码来获取页面元素的位置:
var _x = 0, _y = 0;
do{
_x += el.offsetLeft;
_y += el.offsetTop;
}while(el=el.offsetParent);
return {x:_x,y:_y};
这里有个”offsetParent”问题,所以要写很多兼容的代码,经过不懈的查找终于找到getBoundingClientRect();该方法获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置,他返回的是一个对象,即Object,该对象有是个属性:top,left,right,bottom;这里的top、left和css中的理解很相似,但是right,bottom和css中的理解有点不一样,看示意图:
以前getBoundingClientRect()是IE特有的,目前FF3+,opera9.5+,safari 4,都已经支持这个方法。
可以滚动滚动条之后点红色区域看各个值的变化:
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>
</head>
<body style="width:2000px; height:1000px;">
<div id="demo" style="position:absolute; left:518px; right:100px; width:500px; height:500px; background:#CC0000; top: 114px;">Demo为了方便就直接用绝对定位的元素</div>
<script type="text/javascript">
<span style="white-space: pre;"> </span>document.getElementById('demo').onclick = function() {
if (document.documentElement.getBoundingClientRect) {
alert("left:" + this.getBoundingClientRect().left);
alert("top:" + this.getBoundingClientRect().top);
alert("right:" + this.getBoundingClientRect().right)
alert("bottom:" + this.getBoundingClientRect().bottom);
var X = this.getBoundingClientRect().left + document.documentElement.scrollLeft;
var Y = this.getBoundingClientRect().top + document.documentElement.scrollTop;
alert("Demo的位置是X:" + X + ";Y:" + Y)
}
}
</script>
</body>
</html>
有了这个方法,获取页面元素的位置就简单多了,
var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;
var Y =this.getBoundingClientRect().top+document.documentElement.scrollTop;
以上图片和代码来自:http://www.cnblogs.com/qieqing/archive/2008/10/06/1304399.html




一 个引用通告
[...] 在jquery中获取元素的页面位置,可以很方便的使用offset().left、offset().top来获取,其实在去年有看到过码头的博文:http://www.css88.com/archives/1772 用getBoundingClientRect()来获取页面元素的位置,这技术一不用就会慢慢荒废了,还是记录在blog好,没事翻翻还可以增强记忆,感谢阿里云的朋友~~ document.documentElement.getBoundingClientRect [...]