简体   繁体   English

获取相对于窗口的IFRAME位置

[英]Get IFRAME position relative to the window

I have javascript code running inside an iframe which is served from a different domain than the parent window. 我在iframe中运行javascript代码,该代码是从父窗口以外的域提供的。 Due to security concerns (crossing domains), I can't easily detect the frame's location inside the window. 由于安全问题(跨域),我无法轻易检测到窗口内框架的位置。

However, I have found that if I attach an event to window.mousemove in the frame, I can get the window's ScreenX/Y and the event's ScreenX/Y which gives me a good idea of the offsets from the browser window's upper left corner which is close enough for me - I just want to detect if and how much of the frame is within view. 但是,我发现如果我将一个事件附加到框架中的window.mousemove,我可以得到窗口的ScreenX / Y和事件的ScreenX / Y,这让我很好地了解了浏览器窗口左上角的偏移量。对我来说足够接近 - 我只想检测视图中框架的数量和数量。

So I thought I could pragmatically fire window.mousemove() in the iframe, but then event.ScreenX/Y doesn't get populated. 所以我认为我可以在iframe中实用地激活window.mousemove(),但是不会填充event.ScreenX / Y.

So my question is either: 所以我的问题是:

1) How do I get an iframe's absolute offsets from the window when the frame is on a different domain 2) OR - just as good - how do I pragmatically fire an event that has ScreenX/Y populated? 1)当帧在不同的域上时,如何从窗口获得iframe的绝对偏移量2)或者 - 同样好 - 我如何实际触发已填充ScreenX / Y的事件?

Something like this works for me though I'm not sure if this is exactly what you asked for. 这样的东西对我有用,虽然我不确定这是不是你要求的。 There are 2 things you may still need to account for: 您可能仍需要考虑以下两件事:

  1. Scrolling offset from the browser, but I think this value is available for you to use. 从浏览器滚动偏移量,但我认为您可以使用此值。
  2. Browser header differences, the value I'm currently getting does not deduct the height used by the browser header, nor any padding on the left. 浏览器标题差异,我当前获得的值不会扣除浏览器标题使用的高度,也不会扣除左侧的任何填充。 There are a few ways you could do this though. 有几种方法可以做到这一点。

    a) Create a list of browsers and automatically deduct the best guess on how big the header may be. a)创建一个浏览器列表,并自动扣除关于标头大小的最佳猜测。 b) Do a bit of math using innerHeight but then you still have to figure out how big the windows status bar (or unix or max) is VS the browser header size. b)使用innerHeight进行一些数学计算,但是你仍然需要弄清楚窗口状态栏(或unix或max)对浏览器头大小的影响有多大。

Anyway here is the code I used: 无论如何这里是我使用的代码:

<html>
    <head>
        <title>iframe title</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script type="text/javascript">
        jQuery(document).ready(function(){
           $(document).mousemove(function(e){
                var x = e.screenX - e.pageX - window.screenX;
                var y = e.screenY - e.pageY - window.screenY;
              $('#status').html(x +', ' + y );
           }); 
        })
        </script>       
    </head>
    <body id="doc">
        <h2 id="status">0, 0</h2>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM