offsetParent

查找元素的定位父级元素

属性说明

offsetParent 返回元素的定位父级元素,即距离当前元素最近的、position 不为 static 的祖先元素。

const element = document.getElementById('child');
const parent = element.offsetParent;

console.log(parent.id);  // 定位父级的 ID
  • 如果元素的 position 是 fixed,返回 null
  • 如果所有祖先元素都是 static,返回 body 或 html
  • offsetLeft/offsetTop 是相对于 offsetParent 的位置

示例:查找 offsetParent 链

点击元素查看其 offsetParent

Grandparent (position: relative)
Parent (position: relative)
子元素
(点击我)

offsetParent 链

子元素的 offsetParent: 点击查看
offsetTop: 0px

总结

  • offsetParent 是最近的定位祖先元素
  • fixed 定位的元素 offsetParent 为 null
  • offsetLeft/Top 相对于 offsetParent
  • 理解 offsetParent 对计算元素位置很重要