How to implement swipe gestures for mobile devices?

后端 未结 9 1063
野性不改
野性不改 2020-12-12 14:58

I have an application made in AngularJS which has arrow key navigation to switch views.

I want to implement this navigation using swipe for touch devices. I tried jG

9条回答
  •  时光说笑
    2020-12-12 15:34

    The simplest solution I've found that doesn't require a plugin:

    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;                                             
    };
    

提交回复
热议问题