Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

html - HTML5 with jQuery - e.offsetX is undefined in Firefox

In my HTML5 page, I have a div with mousemove event as follows:

$('#canvas').mousemove(function(e){
    xpos = e.offsetX;
    ypos = e.offsetY;
    $('#mouse').html("X : " + xpos + " ; Y : " + ypos);
});

It works fine with Google Chrome. But in Firefox, both the are giving the value undefined. I have checked it by using Firebug, that is, logged the e object to console. Both offsetX and offsetY are found to be undefined.

When I searched in Google, there was a solution saying I should use layerX and layerY, if both offsetX and offsetY are undefined. But from Firebug, I was not able to find it. And even I had given it a try like this:

xpos = (e.offsetX==undefined)?e.layerX:e.offsetX;
ypos = (e.offsetY==undefined)?e.layerY:e.offsetY;

But that's also giving undefined as values.

I am using the most recent jQuery - v1.8.2. And I am testing in my Firefox v14.0.1

Any ideas or suggestions?


EDIT

Thanks to dystroy and vusan for helping me. The solution to the above issue is as follows:

SOLUTION

$('#canvas').mousemove(function(e){
  $('#cursor').show();
  if(e.offsetX==undefined) // this works for Firefox
  {
    xpos = e.pageX-$('#canvas').offset().left;
    ypos = e.pageY-$('#canvas').offset().top;
  }             
  else                     // works in Google Chrome
  {
    xpos = e.offsetX;
    ypos = e.offsetY;
  }
  $('#mouse').html("X : " + xpos + " ; Y : " + ypos);
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use layerX and layerY in FF and offsetX and offsetY in all other browsers.

$('#canvas').mousemove(function(e){
  xpos = e.offsetX === undefined ? e.originalEvent.layerX : e.offsetX;
  ypos = e.offsetY === undefined ? e.originalEvent.layerY : e.offsetY;

  $('#mouse').html("X : " + xpos + " ; Y : " + ypos);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...