jQuery - Access X and Y coordinates (custom event)

走远了吗. 提交于 2019-12-24 13:50:32

问题


I'm working on an image slide and making it touch enabled. I'm doing this by using a code snippet mentioned in this article: http://blog.safaribooksonline.com/2012/04/18/mapping-mouse-events-and-touch-events-onto-a-single-event/

The author mentions that by using his code, which triggers a normalizing event on touch events, the access of X and Y coordinates is much easier. And that's exactly what I found difficult. I can't seem to access these values at all. I've tried everything I can come up with.

Here's the code: http://jsfiddle.net/BC8dr/3/

normalizeEvent:

function normalizeEvent(type, original, x, y){

    return jQuery.Event(type, {

        pageX: x,
        pageY: y,
        originalEvent: original

    });

}

At the bottom of the code I have commented where I wan't the access:

jQuery(current_slide).bind(TouchMouseEvent.DOWN, onDownEvent);

function onDownEvent(e){

    // This is where I need X and Y coordinate access

    // This will return result: undefined
    var x = e.pageX;
    console.log(x);
}​

So my question is: how do I access X and Y coordinates?

*NOTE: I'm pretty new to JS/jQuery


回答1:


You can recieve the X and Y coordinates using event.clientX event.clientY so in your case

function onDownEvent(e){

    console.log('X = ' + e.clientX);
    console.log('Y = ' + e.clientY);
}​

You can read more here




回答2:


I know this question is old enough but when using e.pageY e.PageX I had problems on Android phones.

How fixed this was by targeting a different value of the event, like:

$(window).on("touchstart", function(event){
        var touchStartY = event.originalEvent.touches[0].clientY;
        var touchStartX = event.originalEvent.touches[0].clientX;
    });
$(window).on("touchmove", function(event){
        var touchMoveY = event.originalEvent.touches[0].clientY;
        var touchMoveX = event.originalEvent.touches[0].clientX;
    });

The first function will give you back the x/y of where you touch in the browser when you start. The second will give you the x/y of where your touch in the browser but is called every time you move your finger.

Instead of targeting "clientX"/"clientY" you can also target:

  • screenX/screenY - which believe is where you touch on the device screen where as client is just within the browsers window.
  • pageX/pageY - which believe takes the value from the top left corner of the document or webpage and not of the browser screen or device screen.


来源:https://stackoverflow.com/questions/13416830/jquery-access-x-and-y-coordinates-custom-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!