我有一个 iframe,在其中我检测到右键单击并将鼠标事件传递给父级中的函数。在这里,(在父函数内部),我有显示自定义上下文菜单的逻辑,并且上下文菜单 html 标记被插入到父 DOM 中。因此需要根据视口(或父 DOM)的鼠标位置,但我收到的是相对于 iframe 的。
我尝试使用 offsetTop 和 offsetParent,但这仅迭代到内页的正文标记。
我有一个 iframe,在其中我检测到右键单击并将鼠标事件传递给父级中的函数。在这里,(在父函数内部),我有显示自定义上下文菜单的逻辑,并且上下文菜单 html 标记被插入到父 DOM 中。因此需要根据视口(或父 DOM)的鼠标位置,但我收到的是相对于 iframe 的。
我尝试使用 offsetTop 和 offsetParent,但这仅迭代到内页的正文标记。
这是我使用的功能:
// 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;
}
这是来自http://codecorner.galanter.net/2012/02/26/absolute-coordinates-of-element-inside-of-iframe/
您可以通过从父文档调用 iframe 来获取顶部和左侧。'my_iframe'
假设您的 iFrame在父文档中具有 id :
offset_left = parent.document.getElementById('my_iframe').offsetLeft;
offset_top = parent.document.getElementById('my_iframe').offsetTop;
但这只适用于 iFrame 中的内容属于同一来源(相同的主机、端口和协议)!
编辑:还在bytes.com上找到了这个类似的问题:iframe relative mouse position
Yuriy 解决方案运行良好,直到该元素是具有 position:absolute 且被滚动的元素的子元素。(我在寻找元素位置而不是鼠标,但我相信你也可以修改它来解决这个问题)
我的修复:
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}
}
至少现在(可能之前也是),您在event
对象(layerX
,screenX
等)上有很多坐标,这意味着如果可以的话,您最好只使用其中一个集合,以避免这种额外的计算 -它在我的用例中大大简化了使用screenX
/screenY
作为基础而不是尝试计算的事情,并且成功了。