如何获得X&iframe中iframe的Y位置

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

本文关键字:iframe 位置 何获得 amp      更新时间:2023-09-26

我在文档上有一个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.offetTop/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>

到目前为止,脚本是这样的:

// 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

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

主Html

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

Iframe代码[irame.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>

window.parent.document.getElementsByTagName('iframe')将引用父窗口中的每个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();