方法el.getBoundingClientRect()
提供相对于视口左上角(0,0
)的结果,而不是相对于元素的父级,而el.offsetTop
,el.offsetLeft
(等)给出相对于父母的结果。
使元素的坐标相对于其父元素的最佳实践是什么? el.getBoundingClientRect()
已修改(如何?)将父级用作(0,0)
坐标,或仍为el.offsetTop
,el.offsetLeft
等等?
答案 0 :(得分:34)
您可以使用getBoundingClientRect()
,只需减去父级的坐标:
var parentPos = document.getElementById('parent-id').getBoundingClientRect(),
childrenPos = document.getElementById('children-id').getBoundingClientRect(),
relativePos = {};
relativePos.top = childrenPos.top - parentPos.top,
relativePos.right = childrenPos.right - parentPos.right,
relativePos.bottom = childrenPos.bottom - parentPos.bottom,
relativePos.left = childrenPos.left - parentPos.left;
console.log(relativePos);
// something like: {top: 50, right: -100, bottom: -50, left: 100}
现在您拥有相对于其父级的子级坐标。
请注意,如果top
或left
坐标为负数,则表示子项在该方向上转义其父项。如果bottom
或right
坐标为正,则相同。
var parentPos = document.getElementById('parent-id').getBoundingClientRect(),
childrenPos = document.getElementById('children-id').getBoundingClientRect(),
relativePos = {};
relativePos.top = childrenPos.top - parentPos.top,
relativePos.right = childrenPos.right - parentPos.right,
relativePos.bottom = childrenPos.bottom - parentPos.bottom,
relativePos.left = childrenPos.left - parentPos.left;
console.log(relativePos);
#parent-id {
width: 300px;
height: 300px;
background: grey;
}
#children-id {
position: relative;
width: 100px;
height: 200px;
background: black;
top: 50px;
left: 100px;
}
<div id="parent-id">
<div id="children-id"></div>
</div>