Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 元素';s相对于其父对象的坐标_Javascript_Html_Css - Fatal编程技术网

Javascript 元素';s相对于其父对象的坐标

Javascript 元素';s相对于其父对象的坐标,javascript,html,css,Javascript,Html,Css,方法el.getBoundingClientRect()给出相对于视口左上角(0,0)的结果,而不是相对于元素的父元素,而el.offsetTop,el.offsetLeft(等)给出相对于父元素的结果 让元素相对于其父元素具有坐标的最佳做法是什么el.getBoundingClientRect()修改(如何)使用父对象作为(0,0)坐标,或者仍然el.offsetTop,el.offsetLeft等等?您可以使用getBoundingClientRect(),只需减去父对象的坐标: var p

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


让元素相对于其父元素具有坐标的最佳做法是什么
el.getBoundingClientRect()
修改(如何)使用父对象作为
(0,0)
坐标,或者仍然
el.offsetTop
el.offsetLeft
等等?

您可以使用
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}
现在您有了子对象相对于其父对象的坐标

请注意,如果
顶部
左侧
坐标为负,则表示该子对象将沿该方向逃逸其父对象。如果
底部
右侧
坐标为正,则相同

工作示例
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=子位置底部-父位置底部,
relativePos.left=childPos.left-parentPos.left;
console.log(relativePos)
#父id{
宽度:300px;
高度:300px;
背景:灰色;
}
#儿童id{
位置:相对位置;
宽度:100px;
高度:200px;
背景:黑色;
顶部:50px;
左:100px;
}


linked-这不考虑CSS转换。我的意思是,如果父级和子级之间存在3D转换,则这不起作用。这将是文档空间中的差异,但不是相对于父空间中的父空间。这在另一个上下文中对我有效,但是如果您想要相对于顶部/左侧的位置,您可能必须执行“relativePos.right=childPos.right-parentPos.left”。与.left相同。如果父对象有一个滚动条,则可能也不起作用:(不起作用,父对象的边框和填充移动了结果。)