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