javascript 元素相对于其父元素的坐标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26423335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Element's coordinates relative to its parent
提问by Basj
The method el.getBoundingClientRect()
gives a result relative to the viewport's top-left corner (0,0
), not relative to an element's parent, whereas el.offsetTop
, el.offsetLeft
(etc.) give a result relative to the parent.
该方法el.getBoundingClientRect()
给出相对于视口左上角 ( 0,0
) 的结果,而不是相对于元素的父元素,而el.offsetTop
, el.offsetLeft
(等) 给出相对于父元素的结果。
What is the best practice to have the coordinates of an element relative to its parent? el.getBoundingClientRect()
modified (how?) to use parent as (0,0)
coordinate, or still el.offsetTop
, el.offsetLeft
and so on?
拥有元素相对于其父元素的坐标的最佳实践是什么?el.getBoundingClientRect()
修改(如何?)使用 parent 作为(0,0)
坐标,或者仍然el.offsetTop
,el.offsetLeft
等等?
回答by Marco Bonelli
You can use getBoundingClientRect()
, simply subtracting the coordinates of the parent:
您可以使用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}
Now you have the coordinates of the child relative to its parent.
现在您有了子项相对于其父项的坐标。
Note that if the top
or left
coordinates are negative, it means that the child escapes its parent in that direction. Same if the bottom
or right
coordinates are positive.
请注意,如果top
或left
坐标为负,则意味着子级在该方向上逃离了其父级。如果bottom
或right
坐标为正,则相同。
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>