从iframe内部获取绝对鼠标位置 [英] Get absolute mouse position from inside iframe

查看:356
本文介绍了从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);
})

这篇关于从iframe内部获取绝对鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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