多级iframe中,获取元素相对于浏览器左上角的坐标(非当前frame)

搜索了好多文章,都不是自己想要的,所以在此贴下自己的解决方案,做个笔记。

1、常规需求:获取当前元素距离左边、顶部的距离

1 var x = $(div).offset().left;
2 var y = $(div).offset().top;

2、当元素处于iframe中时候,上面的方法获取的将是相对于iframe的的距离

此时我的做法是判断当前容器是不是iframe,如果是,则递归查找父级容器。累加每级容器计算的值即可

1 function GetPointInScreen(e, x, y) {
2     var point = e.getBoundingClientRect();
3     x += point.left;
4     y += point.top;
5     if (self != top) {
6         return window.parent.GetPointInScreen(window.parent.$("[name='myIframe']")[0], x, y);
7     }
8     return { x: x, y: y };
9 }

e:要获取坐标值的元素

myIframe:我自己的iframe的name值

3、demo

 1 <body>
 2   <div style="100%;height:100px"></div>
 3   <iframe src="xxx">
 4     <div style="100%;height:100px"></div>
 5     <div style="100%;height:100px" onclick="test(this)"></div>
 6     <script>
 7       function test(e){
 8         var point=GetPointInScreen(e,0,0);
 9         console.log(point);
10       }
11     </script>
12   </iframe>
13 </body>
原文地址:https://www.cnblogs.com/grax/p/13085604.html