HTML5 with jQuery - e.offsetX is undefined in Firefox

前端 未结 5 1113
故里飘歌
故里飘歌 2020-12-13 23:07

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

$(\'#canvas\').mousemove(function(e){
    xpos = e.offsetX;
    ypos = e.offsetY         


        
相关标签:
5条回答
  • 2020-12-13 23:42

    This works fine in firefox and others.

    var offsetRequired = (e.offsetX || e.pageX - $(e.target).offset().left);
    
    0 讨论(0)
  • 2020-12-13 23:43

    Try using layerX and layerY for Firefox and offsetX for other browser.

    If event fired with jquery:

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

    If event fired with javascript:

    xpos = e.offsetX==undefined?e.layerX:e.offsetX;
    ypos = e.offsetY==undefined?e.layerY:e.offsetY;
    
    0 讨论(0)
  • 2020-12-13 23:51

    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);
    });
    
    0 讨论(0)
  • 2020-12-13 23:57

    Firefox actually does support MouseEvent.offsetX and MouseEvent.offsetY after release 39.0, which is released in july 2015.

    0 讨论(0)
  • 2020-12-14 00:00

    You did not find them because its in the originalEvent. try: e.originalEvent.layerX e.originalEvent.layerY

    About the pageX and pageY they are not calculating the same thing. layerX is the left of the object from the first relative/absolute parent. pageX is the left of the object from the page.

    0 讨论(0)
提交回复
热议问题