gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:27:02 25 4
gpt4 key购买 nike

我有这样的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com