How to implement swipe gestures for mobile devices?

后端 未结 9 1138
野性不改
野性不改 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:29

    I like your solution and implemented it on my site - however, with some little improvements. Just wanted to share my code:

    function detectSwipe(id, f) {
        var detect = {
            startX: 0,
            startY: 0,
            endX: 0,
            endY: 0,
            minX: 30,   // min X swipe for horizontal swipe
            maxX: 30,   // max X difference for vertical swipe
            minY: 50,   // min Y swipe for vertial swipe
            maxY: 60    // max Y difference for horizontal swipe
        },
            direction = null,
            element = document.getElementById(id);
    
        element.addEventListener('touchstart', function (event) {
            var touch = event.touches[0];
            detect.startX = touch.screenX;
            detect.startY = touch.screenY;
        });
    
        element.addEventListener('touchmove', function (event) {
            event.preventDefault();
            var touch = event.touches[0];
            detect.endX = touch.screenX;
            detect.endY = touch.screenY;
        });
    
        element.addEventListener('touchend', function (event) {
            if (
                // Horizontal move.
                (Math.abs(detect.endX - detect.startX) > detect.minX)
                    && (Math.abs(detect.endY - detect.startY) < detect.maxY)
            ) {
                direction = (detect.endX > detect.startX) ? 'right' : 'left';
            } else if (
                // Vertical move.
                (Math.abs(detect.endY - detect.startY) > detect.minY)
                    && (Math.abs(detect.endX - detect.startX) < detect.maxX)
            ) {
                direction = (detect.endY > detect.startY) ? 'down' : 'up';
            }
    
            if ((direction !== null) && (typeof f === 'function')) {
                f(element, direction);
            }
        });
    }
    

    Use it like:

    detectSwipe('an_element_id', myfunction);
    

    Or

    detectSwipe('another_element_id', my_other_function);
    

    If a swipe is detected the function myfunction is called with parameter element-id and 'left', 'right', 'up' oder 'down'.

提交回复
热议问题