搜索了好多文章,都不是自己想要的,所以在此貼下自己的解決方案,做個筆記。
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="width:100%;height:100px"></div> 3 <iframe src="xxx"> 4 <div style="width:100%;height:100px"></div> 5 <div style="width: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>
