js 判断页面滚动方向

//监听页面滚动事件
function scrollEvent() {
    window.onscroll = function(e){
        scrollFunc();
        if(scrollDirection == 'down'){
            //页面向下滚动要做的事情
        }
        else if(scrollDirection == 'up'){
            //页面向上滚动要做的事情
        }
    }
}

var scrollAction = {x: 'undefined', y: 'undefined'}, scrollDirection;
function scrollFunc() {
    if (typeof scrollAction.x == 'undefined') {
        scrollAction.x = window.pageXOffset;
        scrollAction.y = window.pageYOffset;
    }
    var diffX = scrollAction.x - window.pageXOffset;
    var diffY = scrollAction.y - window.pageYOffset;
    if (diffX < 0) {
        // Scroll right
        scrollDirection = 'right';
    } else if (diffX > 0) {
        // Scroll left
        scrollDirection = 'left';
    } else if (diffY < 0) {
        // Scroll down
        scrollDirection = 'down';
    } else if (diffY > 0) {
        // Scroll up
        scrollDirection = 'up';
    } else {
        // First scroll event
    }
    scrollAction.x = window.pageXOffset;
    scrollAction.y = window.pageYOffset;
}

你可能感兴趣的:(js 判断页面滚动方向)