Detect scrolling after scrolling distance from current position in browser

后端 未结 3 1790
滥情空心
滥情空心 2021-01-22 13:21

I want to detect if i am scrolling but only after I\'ve scrolled a certain distance from my current location. When I stop scrolling, this distance resets to the current location

3条回答
  •  花落未央
    2021-01-22 13:46

    This would be the simplest approach :

    $(document).ready(function() {
    
    var previous = 0;
    
    $(window).scroll(function() {
    
        var current = $(this).scrollTop();
    
        if (current > previous) // down
        else // up
    
        previous = current;
    });
    });
    

    http://codepen.io/anon/pen/ojxPOg?editors=001

    Using the mousewheel plugin, you'd know even before you've actually started scrolling what the direction is. Might be nice but for mobile the above would still be needed (for the quickest way).

    http://codepen.io/anon/pen/YPmjym?editors=001

    Edit - the first code might not work as expected on touch devices. Panning the screen doesn't actually fire a scroll until you release it (as far as I've experienced). Addressing that would need another script that will listen for touchmove events. Here's one example of how to do that :

    $(window).on('touchstart', function(e) {
    
        var swipe = e.originalEvent.touches,
        start = swipe[0].pageY;
    
        $(this).on('touchmove', function(e) {
    
            var contact = e.originalEvent.touches,
            end = contact[0].pageY,
            distance = end-start;
    
            if (distance < -30) // up
            if (distance > 30) // down
        })
        .one('touchend', function() {
    
            $(this).off('touchmove touchend');
        });
    });
    

    An amount of about 30 pixels is usually treated as a targeted swipe.

提交回复
热议问题