问题
I have an iframe inside which i detect a right click and pass the mouse event to a function in the parent. Here, (inside the parent function), i have the logic to display a custom context menu and the context menu html markup is inserted into the parent DOM. Thus is need the mouse position according to the viewport (or the parent DOM), but what i received is relative to the iframe.
I tried using offsetTop and offsetParent, but this iterated only till the body tag of the innerpage.
回答1:
This is the function I used:
// Define class that will hold Object coordinates
function CTopLeft(i_nTop, i_nLeft) {
this.nTop = i_nTop;
this.nLeft = i_nLeft;
}
function GetTopLeftFromIframe(i_oElem) {
var cTL = new CTopLeft(0, 0);
var oElem = i_oElem;
var oWindow = window;
do {
cTL.nLeft += oElem.offsetLeft;
cTL.nTop += oElem.offsetTop;
oElem = oElem.offsetParent;
if (oElem == null) { // If we reach top of the ancestor hierarchy
oElem = oWindow.frameElement; // Jump to IFRAME Element hosting the document
oWindow = oWindow.parent; // and switching current window to 1 level up
}
} while (oElem)
return cTL;
}
This is from http://codecorner.galanter.net/2012/02/26/absolute-coordinates-of-element-inside-of-iframe/
回答2:
You can get the top and left by calling the iframe from the parent document. Say your iFrame has the id 'my_iframe'
in the parent document:
offset_left = parent.document.getElementById('my_iframe').offsetLeft;
offset_top = parent.document.getElementById('my_iframe').offsetTop;
BUT this will only work if the content in the iFrame belongs to the same origin (same host, port and protocol)!
Edit: also found this similar question on bytes.com: iframe relative mouse position
回答3:
The Yuriy solution works well until the element is a child of an element with position:absolute and that is scrolled. (I was looking for the element position rather than mouse, but I'm sure you could modify this to work for that too)
My fix :
function iframe_offset(e){
var x=e.getBoundingClientRect().x
,y=e.getBoundingClientRect().y
,w=e.ownerDocument.defaultView
do{
e = e.offsetParent
if(e == null){
e = w.frameElement
w = w.parent
if(e){
x += e.offsetLeft+e.scrollLeft
y += e.offsetTop+e.scrollTop
}
}
}while(e)
return {x:x,y:y}
}
来源:https://stackoverflow.com/questions/6572992/determine-the-mouse-position-inside-an-iframe-but-inclusive-of-the-parent