简体   繁体   中英

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

So I thought I could pragmatically fire window.mousemove() in the iframe, but then event.ScreenX/Y doesn't get populated.

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?

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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