jQuery (Swipe vs. Touch) pageX and pageY keep returning 0

前端 未结 4 960
忘掉有多难
忘掉有多难 2020-12-25 14:10

I\'m playing with touchstart and touchend events on my iPhone. I built a sample page that has div that if you touch it and scroll the page, it should return the y coordinate

4条回答
  •  难免孤独
    2020-12-25 15:04

    NULL's answer, above, worked great for me, except that you can't assign startCoords to endCoords in the touchstart-bound function. They then point to the same object so that when endCoords gets updated, so does startCoords. When the touchend event fires, startCoords will always equal endCoords.

    Updated code below. This worked for me on an iPad 3 using Safari on iOS 6.0. Edited also to fix a math and display error and remove Math.abs() inside the touchend-bound function. Also added an event.preventDefault() call inside the touchmove-bound function, so that these would work on Google Chrome on iOS as well.

    var startCoords = {}, endCoords = {};
    
    $(document.body).bind("touchstart", function(event) {
        endCoords = event.originalEvent.targetTouches[0];
        startCoords.pageX = event.originalEvent.targetTouches[0].pageX;
        startCoords.pageY = event.originalEvent.targetTouches[0].pageY;
    });
    
    $(document.body).bind("touchmove", function(event) {
        event.preventDefault();
        endCoords = event.originalEvent.targetTouches[0];
    });
    
    $(document.body).bind("touchend", function(event) {
        $('p').text("Your touch on the axis: " + (endCoords.pageX-startCoords.pageX) + "x, " + (endCoords.pageY-startCoords.pageY) + "y");
    });
    

提交回复
热议问题