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

mar*_*452 5 javascript iframe jquery mouseover

我有一个带有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....
 })
Run Code Online (Sandbox Code Playgroud)

qui*_*ilv 7

一种方法是在父窗口中获取iframe的位置,并将其添加到相对于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);
})
Run Code Online (Sandbox Code Playgroud)