Can one use [removed] method to include detection of scroll direction?

后端 未结 3 1662
走了就别回头了
走了就别回头了 2020-11-30 03:36

Can one use Window.Onscroll method to include detection of scroll direction?

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 04:00

    I had trouble making this work in ie8 (although it is compliant for ie9, FF and Chrome) - all scrolls seem to be detected as horizontal.

    Here is a modified script demo that also works in ie8 and may cover a few more browsers.

    function scrollFunc(e) {
    
       function getMethod() {
            var x = 0, y = 0;
            if ( typeof( window.pageYOffset ) == 'number' ) {
              x = window.pageXOffset;
              y = window.pageYOffset;
            } 
    
            else if( document.body && (document.body.scrollLeft || document.body.scrollTop ) ) {
              x = document.body.scrollLeft;
              y = document.body.scrollTop;
            } 
    
            else if( document.documentElement && (document.documentElement.scrollLeft ||     document.documentElement.scrollTop ) ) {
              x = document.documentElement.scrollLeft;
              y = document.documentElement.scrollTop;
            }
    
             return [x, y];
        }
    
        var xy = getMethod();            
        var xMethod = xy[0];           
        var yMethod = xy[1];
    
        if ( typeof scrollFunc.x == 'undefined' ) {
           scrollFunc.x = xMethod;
           scrollFunc.y = yMethod;
        }
    
        var diffX = scrollFunc.x - xMethod;
        var diffY = scrollFunc.y - yMethod;
    
    
        if( diffX<0 ) {
           // Scroll right
        } else if( diffX>0 ) {
           // Scroll left
        } else if( diffY<0 ) {
           // Scroll down
        } else if( diffY>0 ) {
           // Scroll up
        } else {
           // First scroll event
        }
        scrollFunc.x = xMethod;
        scrollFunc.y = yMethod;
    }
    
    window.onscroll=scrollFunc​
    

提交回复
热议问题