Skip to content

坐标

https://zh.javascript.info/coordinates

浏览器的坐标分为两种

  • 相对 Window(窗口),clientX/clientY
  • 相对 Document(文档),pageX/pageY

page 是 不变的
client 是 相对变化的

getBoundingClientRect

getBoundingClientRect 返回的是相对窗口的坐标

一共会返回 8 个属性

left = x
top = y
width/height
right/bottom

警告

值可能是小数
值也可能是负数
IE 浏览器不支持 x/y

elementFromPoint(x, y)

窗口坐标 (x, y) 处嵌套最多(the most nested)的元素。

如果 坐标为负 或 超过了 window,都会返回 null

js
let centerX = document.documentElement.clientWidth / 2;
let centerY = document.documentElement.clientHeight / 2;

let elem = document.elementFromPoint(centerX, centerY);

elem.style.background = "red";

document 的相对坐标

js
// 获取元素的文档坐标
function getCoords(elem) {
  let box = elem.getBoundingClientRect();

  return {
    top: box.top + window.pageYOffset,
    right: box.right + window.pageXOffset,
    bottom: box.bottom + window.pageYOffset,
    left: box.left + window.pageXOffset,
  };
}