元素的坐标相对于其父

问题描述 投票:16回答:1

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

什么是必须元素相对于其父的坐标的最佳做法? el.getBoundingClientRect()修改(如何?)使用父为(0,0)协调,或仍el.offsetTopel.offsetLeft等等?

javascript html css
1个回答
41
投票

您可以使用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}

现在你有相对于其父孩子的坐标。

请注意,如果topleft坐标为负,这意味着孩子逃逸其父在那个方向。同样,如果bottomright坐标是积极的。

Working example

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);
#parent-id {
    width: 300px;
    height: 300px;
    background: grey;
}

#child-id {
    position: relative;
    width: 100px;
    height: 200px;
    background: black;
    top: 50px;
    left: 100px;
}
<div id="parent-id">
    <div id="child-id"></div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.