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)
现在您拥有相对于其父级的子级坐标.
请注意,如果top
或left
坐标为负数,则表示子项在该方向上转义其父项.如果bottom
或right
坐标为正,则相同.
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)