Detect a finger swipe through JavaScript on the iPhone and Android

How can you detect that a user swiped his finger in some direction over a web page with JavaScript?

I was wondering if there was one solution that would work for websites on both the iPhone and an Android phone.


Simple vanilla JS code sample:

document.addEventListener('touchstart', handleTouchStart, false);        
document.addEventListener('touchmove', handleTouchMove, false);

var xDown = null;                                                        
var yDown = null;                                                        

function handleTouchStart(evt) {                                         
    xDown = evt.touches[0].clientX;                                      
    yDown = evt.touches[0].clientY;                                      
};                                                

function handleTouchMove(evt) {
    if ( ! xDown || ! yDown ) {
        return;
    }

    var xUp = evt.touches[0].clientX;                                    
    var yUp = evt.touches[0].clientY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {
            /* left swipe */ 
        } else {
            /* right swipe */
        }                       
    } else {
        if ( yDiff > 0 ) {
            /* up swipe */ 
        } else { 
            /* down swipe */
        }                                                                 
    }
    /* reset values */
    xDown = null;
    yDown = null;                                             
};

Tested in Android.

Use evt.originalEvent.touches instead of evt.touches if you are working with JQuery.


I found this jquery touchwipe plugin which works on both my first generation ipod touch and my droid incredible. http://www.netcu.de/jquery-touchwipe-iphone-ipad-library


Have you tried hammer.js? http://eightmedia.github.com/hammer.js/ Also works on Windows Phones..

链接地址: http://www.djcxy.com/p/91244.html

上一篇: 滚动查看和图库干扰

下一篇: 通过iPhone和Android上的JavaScript检测手指滑动