React中获取元素位置

React框架使用虚拟DOM代替真实的DOM来优化性能,使用props和state进行属性传递。所以说在react中直接获取DOM元素的位置是不合理的(不利于性能)。那么我们可以使用下面的API:

document.documentElement.getBoundingClientRect

Syntax

oRect = object.getBoundingClientRect()

// 获取当前对象的边界矩形区域

Return Value

Returns a TextRectangle object. Each rectangle has four integer properties (top, left, right, and bottom) that represent a coordinate of the rectangle, in pixels.

//返回值是一个文本矩形对象。每一个矩形有四个属性:(top, left, right, and bottom),可以代表这个矩形的坐标!bingo!

Remarks

This method retrieves an object that exposes the left, top, right, and bottom coordinates of the union of rectangles relative to the client's upper-left corner. In Microsoft Internet Explorer 5, the window's upper-left is at 2,2 (pixels) with respect to the true client.

兼容性:最新的浏览器中坐标是按照左上角为原点进行计算。IE5中,左上角有2px的实际差距。(现在兼容IE5的网站已经不多见了)

还是实际解释下,该方法获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置。。

该方法已经不再是IE Only了,FF3.0+和Opera9.5+已经支持了该方法,可以说在获得页面元素位置上效率能有很大的提高,在以前版本的Opera和Firefox中必须通过循环来获得元素在页面中的绝对位置。

 

 

下面的代码举了个简单的例子,可以滚动滚动条之后点红色区域看各个值的变化。

复制代码代码如下:

<!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>
  <style type="text/css" media="screen">
  body {
    width:1000px;
    height:8000px;
  }
  #demo {
    position: absolute;
    left: 600px;
    right: 100px;
    width: 500px;
    height: 500px;
    background: #CCC;
    top: 114px;
  }
  </style>
</head>
<body>
  <div id="demo">Demo为了方便就直接用绝对定位的元素
  </div>
  <script>
  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);
      let X = this.getBoundingClientRect().left + document.documentElement.scrollLeft;
      let Y = this.getBoundingClientRect().top + document.documentElement.scrollTop;
      alert("Demo的位置是X:" + X + ";Y:" + Y)
    }
  }
  </script>
</body>
</html>

 

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

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

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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值