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

Kei*_* C. 3 html javascript 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>
Run Code Online (Sandbox Code Playgroud)

我已经尝试过window.offsetTop/Left,parent.window.offsetTop/Left,window.clientTop等等我能找到的其他任何东西,但仍然是'未定义'.

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

有任何想法吗?

顺便说一句,我不能使用JQuery.只有JS.

这里有一些细节:

<html>
<body>
<div>
<iframe name="iframe/123/Test">
<html>
<body>
<script src="same domain"></script>
</body>
</html>
</iframe>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

到目前为止,脚本看起来像这样:

// 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>");
Run Code Online (Sandbox Code Playgroud)

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

Document Width: 1566
Document Height: 652
Iframe Width: 300
Iframe Height: 250
Iframe X: undefined
Run Code Online (Sandbox Code Playgroud)

Yog*_*lvi 5

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

主要的Html

<html>
 <body>
   <iframe src='iframe.html' name='iframe_name' id='iframe_id'></iframe>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)