从 iframe 中获取绝对鼠标位置

Get absolute mouse position from inside iframe

我有一个带有 iframe 呈现另一个页面(同一域)的网页。我需要获取鼠标相对于父文档的位置。请记住,iframe 可以双向滚动。我试过使用偏移量但没有运气。

$('#iframe').contents().find('html').on('mousemove', function (e) {

     //gives me location in terms of the iframe but not the entire page. 
     var y = e.pageY; 

     //gives me 0
     var y = $(this).offset().top;

     //more code here....
 })

一种方法是获取 iframe 在父 window 中的位置,并将其添加到相对于 iframe 本身的鼠标位置。扩展下面的代码,

var iframepos = $("#iframe").position();

$('#iframe').contents().find('html').on('mousemove', function (e) { 
    var x = e.clientX + iframepos.left; 
    var y = e.clientY + iframepos.top;
    console.log(x + " " + y);
})

event.clientX、event.clientY 并不适用于所有浏览器。但是,jQuery 有一个解决方案。另外,当您的 iframe 位于另一个 iframe 中时,您会怎么做?我有一个跨浏览器与嵌套 iframe 一起工作的解决方案。

GetPosition: function (event) {
    var $body = $("body");

    var offsetLeft = event.pageX - $body.scrollLeft();
    var offsetTop = event.pageY - $body.scrollTop();

    if (window != parent.window) {
        // event was fired from inside an iframe
        var $frame = parent.$("iframe#" + window.frameElement.id);
        var framePos = $frame.position();
        offsetLeft += framePos.left;
        offsetTop += framePos.top;
    }

    if (parent.window != parent.parent.window) {
        // event was fired from inside an iframe which is inside another iframe
        var $frame = parent.parent.$("iframe#" + parent.window.frameElement.id);
        var framePos = $frame.position();
        offsetLeft += framePos.left;
        offsetTop += framePos.top;
    }

    return [offsetLeft, offsetTop];
}

我希望这是一个完美的解决方案。如果您的 iframe 位于固定布局或绝对定位为模态对话框,它会起作用。但是,如果您的 iframe 位于另一个绝对定位的容器内,则您还必须获取该容器的 .position() 并将其添加到总偏移量中。