元素相对于其父级的坐标 [英] Element's coordinates relative to its parent

查看:154
本文介绍了元素相对于其父级的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()修改(如何?)使用parent作为(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?

推荐答案

您可以使用 getBoundingClientRect(),只需减去父级的坐标:

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

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}

现在您拥有相对于其父级的子级坐标。

Now you have the coordinates of the child relative to its parent.

请注意,如果 top left 坐标是否定,这意味着孩子在那个方向逃脱了它的父母。如果底部坐标为正,则相同。

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.

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>

这篇关于元素相对于其父级的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆