Skip to main content

元素坐标

elem.getBoundingClientRect()

调用该方法会返回一个 DOMRect 对象,该对象上的属性记录了 elem 的左边,其结构如下:

{
x: 200,
y: 200,
width: 102,
height: 102,
top: 200,
right: 302,
bottom: 302,
left: 200,
}
  • x/y 表示元素的左上角相对于窗口的坐标
  • width/height 表示元素实际的可视区域尺寸(border 及其以内)
  • top/bottom 表示元素顶部和底部距离窗口顶部的距离
  • left/right 表示元素左边和右边距离窗口左边的距离

pic.nm

注意事项

top/left 的值可能是负数,原因是 elem 的内容滚动时,可能超出窗口边缘。

document.elementFromPoint(x, y)

该方法用于获取当前窗口 (x, y) 坐标处嵌套最多的元素。

窗口坐标

一般使用 position: fixed 与 elem.getBoundingClientRect() 一起使用。

窗口内容坐标

一般使用 position: absolute 与 elem.getBoundingClientRect() 一起使用。