记一下 Element.getBoundingClientRect() 这个 API 和 ES6 析构赋值重命名语法

276 阅读1分钟

Element.getBoundingClientRect()

  • 先是遇到一个新的 API Element.getBoundingClientRect()  ,此方法返回元素的大小及其相对于视口的位置。

  • 我需要获取 x 元素的 left 值和 y 元素的 left 值,取他们之间的差值

  • 先获取 x 元素的 left 值和 y 元素的 left 值

const {left} = x.getBoundingClientRect()
const {left} = y.getBoundingClientRect()
  • 上面用到了析构赋值。简单复习一下:以上代码意思是,获取到 x.getBoundingClientRect 的 left

ES6 析构赋值重命名语法

  • 问题来了,他们都是 left,那怎么才能取差值呢?
  • 析构赋值重命名语法即可,把 x 元素的 left 命名成 left1, y 元素的 left 命名成 left2,代码如下:
const { left: left1 } = x.getBoundingClientRect()
const { left: left2 } = y.getBoundingClientRect()
  • 然后就可以算差值了
const left = left2 - left1