Detect left/right-swipe on touch-devices, but allow up/down-scrolling

前端 未结 5 1475
逝去的感伤
逝去的感伤 2020-12-04 11:24

I need to detect and react to left/right-swipes, but want to give the user the ability to scroll on the same element, so as long as he moves his finger only left/right with

5条回答
  •  广开言路
    2020-12-04 11:52

    Detecting left and right while touch is still moving.

    This is done with saving last position and using timeout for erasing last position after touchmove stop.

    var currentX;
    var lastX = 0;
    var lastT;
    $(document).bind('touchmove', function(e) {
        // If still moving clear last setTimeout
        clearTimeout(lastT);
    
        currentX = e.originalEvent.touches[0].clientX;
    
        // After stoping or first moving
        if(lastX == 0) {
            lastX = currentX;
        }
    
        if(currentX < lastX) {
            // Left
        } else if(currentX > lastX){
            // Right
        }
    
        // Save last position
        lastX = currentX;
    
        // Check if moving is done
        lastT = setTimeout(function() {
            lastX = 0;
        }, 100);
    });
    

提交回复
热议问题