JS - 子页面中获取其所在的iframe坐标方法(相对屏幕左上角的位置)
前端开发时,我们常常会使用 iframe 标签来嵌入子页面。而在子页面中有时需要知道父页面里该 iframe 所在的位置坐标,从而计算一些偏移量,这个通过 js 即可实现,下面通过样例进行演示。

(2)子页面 child.html 代码如下,首先从父页面中找到所属的 iframe,然后通过 getBoundingClientRect() 方法便可以获取该 iframe 元素的大小及其相对于视口的位置:

1,样例代码
(1)父页面 father.html 代码很简单,就是使用 iframe 标签加载子页面:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> 父页面 <div style="position: absolute;left:150px;top:100px;right:10px;bottom:10px"> <iframe src="child.html" frameborder="0" scrolling="no" width="100%" height="100%"></iframe> </div> </body> </html>
(2)子页面 child.html 代码如下,首先从父页面中找到所属的 iframe,然后通过 getBoundingClientRect() 方法便可以获取该 iframe 元素的大小及其相对于视口的位置:
注意:该方法前提是子页面与父页面必须在同一个域下(域名、端口一样)。如果不是同一个域,子页面是无法访问父页面的方法和 dom 元素的。访问时会报如下错误:
- Uncaught DOMException: Blocked a frame with origin "http://xxxxx" from acceesing a cross-origin frame.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript"> // 获取父页面里所有的iframe let iframes = window.parent.document.getElementsByTagName('iframe'); // 获取当前页面所在的 iframe let iframe; for (var i = 0; i < iframes.length; i++) { if (iframes[i].src == location.href) { iframe = iframes[i]; break; } } //返回值是一个包含坐标位置以及宽高尺寸的对象 let rect = iframe.getBoundingClientRect() // 输出结果 console.log("x:", rect.x); console.log("y:", rect.y); console.log("width:", rect.width); console.log("height:", rect.height); console.log("rect:", rect); </script> </head> <body style="background-color:beige"> 子页面 </body> </html>
2,运行结果
页面打开后,查看控制台可以看到输出如下相关信息: