我有HTML像這樣:如何獲得相對於頂窗口的視口的iframe的位置?
<body>
[some stuff]
<iframe src="pageWithMyScript.html"></iframe>
[more stuff]
</body>
我想找到相對iframe的位置window.top(和/或top.document)從iframe中運行的腳本。 (理想情況下,這將是沒有任何框架,但我可以總是解構它們如何做,我想。)
我有HTML像這樣:如何獲得相對於頂窗口的視口的iframe的位置?
<body>
[some stuff]
<iframe src="pageWithMyScript.html"></iframe>
[more stuff]
</body>
我想找到相對iframe的位置window.top(和/或top.document)從iframe中運行的腳本。 (理想情況下,這將是沒有任何框架,但我可以總是解構它們如何做,我想。)
這隻能工作,如果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;
};
多一點簡單的像這樣:
function computeFrameOffset(win, dims) {
dims = (typeof dims === 'undefined')?{ top: 0, left: 0}:dims;
if (win !== top) {
var rect = win.frameElement.getBoundingClientRect();
dims.left += rect.left;
dims.top += rect.top;
computeFrameOffset(win.parent, dims);
}
return dims;
};
小幅盤整:
function computeFrameOffset(win, dims) {
dims = (typeof dims === 'undefined')?{ top: 0, left: 0}:dims;
if (win !== top) {
var rect = win.frameElement.getBoundingClientRect();
dims.left += rect.left;
dims.top += rect.top;
dims = computeFrameOffset(win.parent, dims); // recursion
}
return dims;
};
事情是'window.frameElement'無法在跨域iframe中訪問:/ – 2016-11-22 08:33:13
非常感謝以上。略有改進:以上不考慮已經滾動的窗口。我已經更新了上面的代碼來解釋這一點。 – 2013-04-29 16:28:50
你也可以使用frames [i] == window.frameElement檢查匹配 – 2013-12-05 18:50:56
爲什麼你不使用'frame = window.frameElement'而不是在父窗口中獲取整組iframe並檢查哪一個是正確的一個? – 2015-05-26 07:18:55