元素相对于其父级的坐标

Bas*_*asj 19 html javascript css

该方法el.getBoundingClientRect()给出了结果相对于视口的左上角(一0,0),而不是相对于一个元素的父,而el.offsetTop,el.offsetLeft(等)得到的结果相对于父一个.

使元素的坐标相对于其父元素的最佳实践是什么?el.getBoundingClientRect()修改(如何?)使用父为(0,0)坐标,或静止el.offsetTop,el.offsetLeft等等?

Mar*_*lli 42

您可以使用getBoundingClientRect(),只需减去父级的坐标:

var parentPos = document.getElementById('parent-id').getBoundingClientRect(),
    childPos = document.getElementById('child-id').getBoundingClientRect(),
    relativePos = {};

relativePos.top = childPos.top - parentPos.top,
relativePos.right = childPos.right - parentPos.right,
relativePos.bottom = childPos.bottom - parentPos.bottom,
relativePos.left = childPos.left - parentPos.left;

console.log(relativePos);
// something like: {top: 50, right: -100, bottom: -50, left: 100}
Run Code Online (Sandbox Code Playgroud)

现在您拥有相对于其父级的子级坐标.

请注意,如果topleft坐标为负数,则表示子项在该方向上转义其父项.如果bottomright坐标为正,则相同.

工作实例

var parentPos = document.getElementById('parent-id').getBoundingClientRect(),
    childPos = document.getElementById('child-id').getBoundingClientRect(),
    relativePos = {};

relativePos.top = childPos.top - parentPos.top,
relativePos.right = childPos.right - parentPos.right,
relativePos.bottom = childPos.bottom - parentPos.bottom,
relativePos.left = childPos.left - parentPos.left;

console.log(relativePos);
Run Code Online (Sandbox Code Playgroud)
#parent-id {
    width: 300px;
    height: 300px;
    background: grey;
}

#child-id {
    position: relative;
    width: 100px;
    height: 200px;
    background: black;
    top: 50px;
    left: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="parent-id">
    <div id="child-id"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 这不考虑 CSS 转换。 (3认同)
  • 我的意思是,如果父子之间存在 3D 转换,这将不起作用。这将是文档空间的差异,但与父空间中的父级无关。 (3认同)
  • 如果父级有滚动,它也可能不起作用:( (3认同)
  • 这在另一个上下文中对我有用,但是如果您想要相对于顶部/左侧的位置,您可能必须执行“relativePos.right = childPos.right -parentPos.left”。.left 也一样。 (2认同)