Get absolute mouse position from inside iframe

2019-05-09 13:09发布

问题:

I have a webpage with an iframe rendering another page (same domain). I need to get the mouse position in relation to the parent document. Keep in mind the iframe can scroll both ways. I've tried using offset with no luck.

$('#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....
 })

回答1:

One way to do it would be to get the position of the iframe in the parent window and add it to the mouse position relative to the iframe itself. Extending your code below,

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);
})


回答2:

event.clientX, event.clientY do not work in every browser. However, jQuery has a solution which does. Also, what do you do when your iframe is inside another iframe? I have a solution which works cross browser with nested iframes.

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];
}

I wish this were a perfect solution. It works if your iframe is positioned in a fixed layout or absolutely positioned as a modal dialog. However, if your iframe is inside another absolutely positioned container, you will have to get the .position() of that container as well and add it to the total offsets.