如何从 iframe 中获取 iframe 的 X 和 Y 位置?

How to get the X & Y position of an iframe from within the Iframe?

我在文档上有一个 iframe。使用 javascript,我可以获得 iframe 的宽度和高度以及文档的宽度和高度。我现在需要从 iframe 中获取文档中 iframe 的 x,y 位置。

代码类似于:

<html>
<iframe>
var documentWidth = parent.window.innerWidth;
var documentHeight = parent.window.innerHeight;
var iframeWidth = window.innerWidth;
var iframeHeight = window.innerHeight;
var iframeX = ????
</iframe>
<html>

我已经尝试了 window.offsetTop/Left、parent.window.offsetTop/Left、window.clientTop 等以及我能找到的任何其他东西,但不断得到 'undefined'.

两者都在同一台服务器上,所以我认为我没有跨域问题。

有什么想法吗?

顺便说一句,我不能为此使用 JQuery。仅限 JS。

这里有更多细节:

<html>
<body>
<div>
<iframe name="iframe/123/Test">
<html>
<body>
<script src="same domain"></script>
</body>
</html>
</iframe>
</div>
</body>
</html>

到目前为止,脚本如下所示:

// JavaScript Document
var documentWidth = parent.window.innerWidth;
var documentHeight = parent.window.innerHeight;
var iframeWidth = window.innerWidth;
var iframeHeight = window.innerHeight;
var iframeName = window.name;
var iframeX = window.parent.document.getElementsByName(iframeName).offsetLeft;

//Var Dumps
document.write("Document Width: "+documentWidth+"<br>");
document.write("Document Height: "+documentHeight+"<br>");
document.write("Iframe Width: "+iframeWidth+"<br>");
document.write("Iframe Height: "+iframeHeight+"<br>");
document.write("Iframe X: "+iframeX+"<br>");

我在 iframe 的页面上得到以下结果:

Document Width: 1566
Document Height: 652
Iframe Width: 300
Iframe Height: 250
Iframe X: undefined

window.parent.document.getElementsByTagName('iframe') 将引用父 window 中的每个 iframe。从那里您可以通过循环并检查 src 属性找到您的特定 iframe。

获得 iframe 后,您可以使用 element.getBoundingRect() 中的属性获取它的尺寸和位置。

var iframes = window.parent.document.getElementsByTagName('iframe');

var yourURL = 'test.com';
var iframe;

for (var i = 0; i < iframes.length; i++) {
    if (iframes[i].src == 'test.com') {
        iframe = iframes[i];
        break;
    }
}

var rect = iframe.getBoundingClientRect();

由于两个文件都在同一台服务器上,所以您没有跨域问题,您可以尝试以下解决方案:

主要Html

<html>
 <body>
   <iframe src='iframe.html' name='iframe_name' id='iframe_id'></iframe>
 </body>
</html>

iframe 代码 [iframe.html]:

<html>
  <body>
    <script type="text/javascript">
       var documentWidth = parent.window.innerWidth;
       var documentHeight = parent.window.innerHeight;
       var iframeWidth = window.innerWidth;
       var iframeHeight = window.innerHeight;
       // Get Left Position
       var iframeX = window.parent.document.getElementById('iframe_id').offsetLeft;
       // Get Top Position
       var iframeY = window.parent.document.getElementById('iframe_id').offsetTop;
    </script>
  </body>
</html>