event.offsetX in Firefox

后端 未结 11 1788
既然无缘
既然无缘 2020-11-27 16:45





        
相关标签:
11条回答
  • 2020-11-27 16:52

    Unfortunately no solution worked for me.

    I found a good implementation here:

    var target  = e.target || e.srcElement,
                  rect    = target.getBoundingClientRect(),
                  offsetX = e.clientX - rect.left,
                  offsetY  = e.clientY - rect.top;
    
    e.offsetX   = offsetX;
    e.offsetY   = offsetY;
    
    0 讨论(0)
  • 2020-11-27 16:52

    This question needs an updated answer.


    First, as I mentioned in a comment, regarding all of the older answers using layerX and layerY:

    "This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future."

    (Source: developer.mozilla.org/en-US/docs/Web/API/UIEvent/layerX)


    Second, I've discovered that when you console.log(event) in Firefox, offsetX and offsetY show 0, but when you console.log(event.offsetX), it is not 0. So be careful because you may be being lied to.

    This behavior is explained here:

    Logging objects

    Don't use console.log(obj), use console.log(JSON.parse(JSON.stringify(obj))).

    This way you are sure you are seeing the value of obj at the moment you log it. Otherwise, many browsers provide a live view that constantly updates as values change. This may not be what you want.

    (Also note that JSON.stringify() will not do what you want here... It doesn't stringify the entire event object.)

    0 讨论(0)
  • 2020-11-27 16:55

    But , what you will do if there is not layerX,layerY fields ?

     var xe=e.offsetX,ye=e.offsetY;
      if(!xe){
         xe=e.clientX - $(e.target).offset().left;
      }
      if(!ye){
        ye= e.clientY - $(e.target).offset().top;
      }
    
    0 讨论(0)
  • 2020-11-27 16:59

    If some still needs a solutions this one works perfect in Firefox:

    var x = e.offsetX || e.originalEvent.layerX;
    var y = e.offsetY || e.originalEvent.layerY;
    
    0 讨论(0)
  • 2020-11-27 17:02

    From a JQuery bug tracker page - a nice polyfill is this:

    var offX  = (e.offsetX || e.pageX - $(e.target).offset().left);
    

    .. where e is the event returned from a jquery event. Obviously, only if you've got Jquery already on your project, otherwise will have to do the offset() stuff manually.

    0 讨论(0)
  • 2020-11-27 17:07

    Try layerX, layerY

    var x = (e.offsetX === undefined) ? e.layerX : e.offsetX;
    var y = (e.offsetY === undefined) ? e.layerY : e.offsetY;
    

    FIDDLE

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