Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
461 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use getBoundingClientRect(), simply subtracting the coordinates of the parent:

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.

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...