用getBoundingClientRect()来获取页面元素的位置

以前绝大多数的使用下面的代码来获取页面元素的位置:

1. var _x = 0, _y = 0;
2. do{
3. _x += el.offsetLeft;
4. _y += el.offsetTop;
5. }while(el=el.offsetParent);
6. return {x:_x,y:_y};

这里有个”offsetParent”问题,所以要写很多兼容的代码,经过不懈的查找终于找到getBoundingClientRect();该方法获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置,他返回的是一个对象,即Object,该对象有是个属性:top,left,right,bottom;这里的top、left和css中的理解很相似,但是right,bottom和css中的理解有点不一样,看示意图:

2008100603035335

2008100603040663

以前getBoundingClientRect()是IE特有的,目前FF3+,opera9.5+,safari 4,都已经支持这个方法。

可以滚动滚动条之后点红色区域看各个值的变化:

01. < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02.   
03. <html xmlns="http://www.w3.org/1999/xhtml">
04.   
05. <head>
06.   
07. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
08.   
09. <title>Demo</title>
10.   
11. </head>
12.   
13. <body style="width:2000px; height:1000px;">
14.   
15. <div id="demo" style="position:absolute; left:518px; right:100px; width:500px; height:500px; background:#CC0000; top: 114px;">Demo为了方便就直接用绝对定位的元素</div>
16.   
17. <script type="text/javascript">
18.   
19. <span style="white-space: pre;"> </span>document.getElementById('demo').onclick = function() {
20.   
21. if (document.documentElement.getBoundingClientRect) {
22.   
23. alert("left:" + this.getBoundingClientRect().left);
24.   
25. alert("top:" + this.getBoundingClientRect().top);
26.   
27. alert("right:" + this.getBoundingClientRect().right)
28.   
29. alert("bottom:" + this.getBoundingClientRect().bottom);
30.   
31. var X = this.getBoundingClientRect().left + document.documentElement.scrollLeft;
32.   
33. var Y = this.getBoundingClientRect().top + document.documentElement.scrollTop;
34.   
35. alert("Demo的位置是X:" + X + ";Y:" + Y)
36.   
37. }
38.   
39. }
40.   
41. </script>
42.   
43. </body>
44.   
45. </html>

有了这个方法,获取页面元素的位置就简单多了,

var X= this.getBoundingClientRect().left+document.documentElement.scrollLeft;

var Y =this.getBoundingClientRect().top+document.documentElement.scrollTop;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值