javascript - 如何获取 iframe 相对于顶部窗口视口(viewport)的位置?

标签 javascript iframe

我有这样的 html:

<body>
    [some stuff]
    <iframe src="pageWithMyScript.html"></iframe>
    [more stuff]
</body>

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

最佳答案

这只有在 iframe 和容器共享 same origin 时才有效, 否则 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;
};

关于javascript - 如何获取 iframe 相对于顶部窗口视口(viewport)的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9675445/

相关文章:

javascript - 调整 ng-repeat 过滤器的大小

javascript - 无法使用 AJAX 请求的字符串结果

javascript - 在 YUI Pure CSS 中更改较小宽度屏幕上的 div 顺序

javascript - 刷新时淡出并进入 iframe?

javascript - postMessage 源 IFrame

javascript - 未捕获的 SecurityError : Blocked a frame with origin . .. 来自访问具有来源的框架

javascript - 调整定位的背景图像

javascript - 创建自定义颜色集 TinyMCE

javascript - trim 在 IE7 中不起作用

angularjs - 使用iframe从youtube到ionic项目在单页上播放视频