onscroll 判断方向

2018-01-27  本文已影响658人  萤火虫de梦

单纯判断方向

function scroll( fn ) {  
    var beforeScrollTop = document.body.scrollTop,  
        fn = fn || function() {};  
    window.addEventListener("scroll", function() {  
        var afterScrollTop = document.body.scrollTop,  
            delta = afterScrollTop - beforeScrollTop;  
        if( delta === 0 ) return false;  
        fn( delta > 0 ? "down" : "up" );  
        beforeScrollTop = afterScrollTop;  
    }, false);  
}  


scroll(function(direction) { console.log(direction) });  

以上方法手机苹果浏览器事件会跳动,解决方法及代码改进

scrollDirect: function (fn) {  
    var beforeScrollTop = document.body.scrollTop;  
    fn = fn || function () {  
    };  
    window.addEventListener("scroll", function (event) {  
        event = event || window.event;  
  
        var afterScrollTop = document.body.scrollTop;  
        delta = afterScrollTop - beforeScrollTop;  
        beforeScrollTop = afterScrollTop;  
  
        var scrollTop = $(this).scrollTop();  
        var scrollHeight = $(document).height();  
        var windowHeight = $(this).height();  
        if (scrollTop + windowHeight > scrollHeight - 10) {  //滚动到底部执行事件  
            fn('up');  
            return;  
        }  
        if (afterScrollTop < 10 || afterScrollTop > $(document.body).height - 10) {  
            fn('up');  
        } else {  
            if (Math.abs(delta) < 10) {  
                return false;  
            }  
            fn(delta > 0 ? "down" : "up");  
        }  
    }, false);  
}  
 

//调用方法
  var upflag=1;  
  var  downflag= 1;  
   //scroll滑动,上滑和下滑只执行一次!  
crollDirect(function (direction) {  
       if (direction == "down") {  
           if (downflag) {  
               $(".footer_wrap").slideUp(200);  
               downflag = 0;  
              upflag = 1;  
           }  
       }  
       if (direction == "up") {  
           if (upflag) {  
               $(".footer_wrap").slideDown(200);  
              downflag = 1;  
               upflag = 0;  
           }  
       }  
});

滚动条滚动到底部和头部判断

BottomJumpPage: function () {  
            var scrollTop = $(this).scrollTop();  
            var scrollHeight = $(document).height();  
            var windowHeight = $(this).height();  
            if (scrollTop + windowHeight == scrollHeight) {  //滚动到底部执行事件  
                    console.dir("我到底部了");  
  
            }  
            if (scrollTop == 0) {  //滚动到头部部执行事件  
            console.dir("我到头部了");  
  
            }  
 }  
 

$(window).scroll(BottomJumpPage); 
上一篇下一篇

猜你喜欢

热点阅读