Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.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 如何获取元素从元素顶部到容器的坐标?_Javascript_Jquery - Fatal编程技术网

Javascript 如何获取元素从元素顶部到容器的坐标?

Javascript 如何获取元素从元素顶部到容器的坐标?,javascript,jquery,Javascript,Jquery,我正试图得到图像上盒子的坐标。坐标应基于图像本身,而不是屏幕大小。我目前正在使用getBoundingClientRect。如何根据图像(框处于打开状态,而不是窗口大小)检索坐标 我尝试过的代码: 我发现这篇文章是这样写的:但那是7年前的事了……你可以使用元素位置和容器位置之间的差异。我像你一样尝试使用,但要小心,因为目前不支持InternetExpolor、Edge或Safari const getBoundingClientRect\u RelativeToParent=元素=>{ con

我正试图得到图像上盒子的坐标。坐标应基于图像本身,而不是屏幕大小。我目前正在使用getBoundingClientRect。如何根据图像(框处于打开状态,而不是窗口大小)检索坐标

我尝试过的代码:
我发现这篇文章是这样写的:但那是7年前的事了……

你可以使用元素位置和容器位置之间的差异。我像你一样尝试使用,但要小心,因为目前不支持InternetExpolor、Edge或Safari

const getBoundingClientRect\u RelativeToParent=元素=>{ const domRect=element.getBoundingClientRect, parentDomRect=element.parentElement.getBoundingClientRect 返回新的DOMRectdomRect.left-parentDomRect.left,domRect.top-parentDomRect.top,domRect.width,domRect.height } console.loggetBoundingClientRect\u RelativeToParentdocument.querySelector.child .家长{ 宽度:500px; 高度:300px; 左边距:200px; 利润上限:200px; 左侧填充:30px; 填充顶部:30px; 背景:绿色; } .孩子{ 宽度:100px; 高度:50px; 背景:红色 } 身体{ 背景:蓝色 }
为什么7年前的答案今天不再适用?
var rect = div[index].getBoundingClientRect();