美文网首页
js 判断页面滚动方向

js 判断页面滚动方向

作者: 造轮子的蜗牛 | 来源:发表于2017-12-08 10:00 被阅读0次
    //监听页面滚动事件
    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 判断页面滚动方向

          本文链接:https://www.haomeiwen.com/subject/yeosixtx.html