从iframe内部获取绝对鼠标位置

从iframe内部获取绝对鼠标位置

问题描述:

我有一个带有iframe的网页呈现另一个页面(同一个域)。我需要获取与父文档相关的鼠标位置。请注意,iframe可以双向滚动。我尝试过使用偏移而没有运气。

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


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

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