确定iframe内的鼠标位置,但包含父级 [英] Determine the mouse position inside an iframe, but inclusive of the parent

查看:148
本文介绍了确定iframe内的鼠标位置,但包含父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个iframe,我在其中检测到右键并将鼠标事件传递给父级中的函数。这里,(在父函数内),我有逻辑显示自定义上下文菜单,上下文菜单html标记插入父DOM。因此需要根据视口(或父DOM)的鼠标位置,但我收到的是相对于iframe。

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.

我尝试使用offsetTop和offsetParent,但是这只迭代到内页的body标签。

I tried using offsetTop and offsetParent, but this iterated only till the body tag of the innerpage.

推荐答案

这是我使用的函数:

// 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-of-iframe /

这篇关于确定iframe内的鼠标位置,但包含父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆