如何获取iframe相对于顶部窗口视口的位置?

spr*_*man 3 javascript iframe

我有这样的HTML:

<body>
    [some stuff]
    <iframe src="pageWithMyScript.html"></iframe>
    [more stuff]
</body>
Run Code Online (Sandbox Code Playgroud)

我想从iframe内运行的脚本中找到相对于window.top(和/或top.document)的iframe的位置.(理想情况下,这可能没有任何框架,但我想总是可以解构他们是如何做到这一点的.)

spr*_*man 6

这只能在iframe和容器共享相同的源时才能工作,否则必须设置CORS(为此,您需要访问这两个域)

/**
 * Calculate the offset of the given iframe relative to the top window.
 * - Walks up the iframe chain, checking the offset of each one till it reaches top
 * - Only works with friendly iframes. https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Cross-origin_script_API_access 
 * - Takes into account scrolling, but comes up with a result relative to 
 *   top iframe, regardless of being visibile withing intervening frames.
 * 
 * @param window win    the iframe we're interested in (e.g. window)
 * @param object dims   an object containing the offset so far:
 *                          { left: [x], top: [y] }
 *                          (optional - initializes with 0,0 if undefined) 
 * @return dims object above
 */
var computeFrameOffset = function(win, dims) {
    // initialize our result variable
    if (typeof dims === 'undefined') {
        var dims = { top: 0, left: 0 };
    }

    // find our <iframe> tag within our parent window
    var frames = win.parent.document.getElementsByTagName('iframe');
    var frame;
    var found = false;

    for (var i=0, len=frames.length; i<len; i++) {
        frame = frames[i];
        if (frame.contentWindow == win) {
            found = true;
            break;
        }
    }

    // add the offset & recur up the frame chain
    if (found) {
        var rect = frame.getBoundingClientRect();
        dims.left += rect.left;
        dims.top += rect.top;
        if (win !== top) {
            computeFrameOffset(win.parent, dims);
        }
    }
    return dims;
};
Run Code Online (Sandbox Code Playgroud)