在javascript中检测Firefox中的鼠标位置

时间:2012-10-01 02:04:30

标签: javascript

我正试图通过鼠标移动事件检测元素内的鼠标位置,但它在Firefox中不起作用。

function mouseover_imageChange(imgid,imgArr) {
    var x= event.pageX- jQuery("#"+imgid).offset().left;
    var y= event.pageY- jQuery("#"+imgid).offset().top;
}

有关如何使其在所有浏览器中都有效的想法,以及需要传递给函数的参数吗?

谢谢, Muhtu

2 个答案:

答案 0 :(得分:1)

既然你似乎在使用jQuery,为什么不使用这样的东西呢?

$(document).ready(function () {
    var startImgTracker = function (e) {
        $(this).mousemove(function (e) {
            console.log(JSON.stringify({
                "x": e.pageX,
                "y": e.pageY,
                "relativeX": e.pageX - $(this).offset().left,
                "relativeY": e.pageY - $(this).offset().top
            }));
        });
    };
    var stopImgTracker = function (e) {
        $(this).unbind('mousemove');
    };
    $('img').hover(startImgTracker, stopImgTracker);
});

使用hover事件触发mousemove处理程序(这是您想要的)和“停止”hover事件以取消绑定mousemove。确保包含一个事件参数以获取当前pageXpageY

这应该适用于任何运行jQuery的浏览器。

答案 1 :(得分:0)

@Muthu

以下是“在视口中获取鼠标的X和Y坐标”的工作演示“http://jsfiddle.net/XsqBz/

请在下面找到完整的来源。享受。

<!doctype html> 
<html lang="en">
<head> 
<title>jQuery: Getting X and Y coordinates of the mouse in the viewport</title> 
<style> 
html{background:#f9f9f9;background-color:#f9f9f9;} 

body{background:#fff;background-color:#fff;color:#666;font-family:"Lucida Grande",Verdana,Arial,Georgia,"Bitstream Vera Sans","Bitstream Charter",sans-serif,serif;margin:2em auto;width:700px;padding:1em 2em;-moz-border-radius:11px;-khtml-border-radius:11px;-webkit-border-radius:11px;border-radius:11px;border:1px solid #dfdfdf;} 

body{ 
font-size:11px; 
line-height:15px; 
background:#fff;
background-color:#fff; 
color:#666; 
margin-left:20px; 
} 

strong{font-size:12px;}
a:link{color:#0066CC;}
a:hover{color:#FF6600;}
a:visited{color:#003366;}
a:active{color:#9DCC00;} 

p{font-size:18px;} 

.relativeX, .relativeY{color:#666;font-size:13pt;} 
.relativeX{font-size:48pt;color:#fc0;position:relative;top:-20px;left:30px;} 
.relativeY{font-size:52pt;position:relative;top:-09px;left:-10px;} 
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head> 
<body> 
<!-- Move mouse over div to get position --> 
<div style="margin:10px;height:400px;width:90%;min-width:420px;background:#ccc;padding:20px;border:1px dotted #777;display:block;"> 
  relative to this 
</div>  
<script> 
(function($) { 
$(document).bind('contextmenu', function(){ 
  return false; 
}); 

  $('div').mousemove(function(e){ 
    // Relative to this div element instead of document 
    var relativeX = e.pageX - this.offsetLeft; 
    var relativeY = e.pageY - this.offsetTop;
    $(this).html('releativeX = <span class="relativeX">' + relativeX + '</span>, releativeY = <span class="relativeY">' + relativeY + '</span>'); 
  }); 
})(jQuery); 
</script>
</body> 
</html>