首屏翻页插件封装 - VicSh/my-web-log GitHub Wiki

需求

实现首屏随鼠标滚轮滚动的速度而翻页。

    function ScrollPage(obj,callback) {
      this.obj = obj;
      this.h = 0;
      this.ev = null;
      this.delta = 0;
      this.callback = callback;
      this.init();
    }

    ScrollPage.prototype = {
      init: function () {
        document.getElementsByTagName('body')[0].style.overflow = 'hidden';
        var _this = this;
        // 初始化,判断浏览器类型,处理兼容性
        if ((navigator.userAgent.toLowerCase().indexOf("firefox")!=-1)){
          document.addEventListener("DOMMouseScroll",function(event) {
            _this.scrollFun.call(_this, event)
          },false);
        }
        else if (document.addEventListener) {
          document.addEventListener("mousewheel",function(event) {
            _this.scrollFun.call(_this, event)
          },false);
        }
        else if (document.attachEvent) {
          document.attachEvent("onmousewheel",function(event) {
            _this.scrollFun.call(_this, event)
          });
        }
        else{
          document.onmousewheel = function(event) {
            _this.scrollFun.call(_this, event)
          };
        }
      },
      scrollFun: function (e) {
        this.ev = e || window.event;
        // 因为chrome浏览器滚轮每一步滚动三行,单行滚动距离是120,而火狐的滚动距离是3,所以这里同步滚动速度
        // chrome浏览器滚动的距离是负的,所以加了个负号,取正
        this.delta = (this.ev.wheelDelta) ? -this.ev.wheelDelta / 120 : (this.ev.detail || 0) / 3;
        if (this.h < this.obj.offsetHeight && this.h >= 0) {
          this.h += (this.delta*10);
          // transform只做了高级浏览器的处理
          if (this.h <= 0) {
            this.obj.style.transform = 'translate3d(0, 0, 0)'
          } else {
            this.obj.style.transform = 'translate3d(0, '+(-this.h)+'px, 0)'
          }
        } else if ( this.delta > 0 && this.h < 0) {
          this.h = 0
          this.obj.style.transform = 'translate3d(0, 0, 0)'
        } else if (this.h >= this.obj.offsetHeight) {
          document.getElementsByTagName('body')[0].style.overflow = 'auto';
          // 翻页完成的回调函数
          this.callback && this.callback()
        }
      }
    }
    
    new ScrollPage(document.getElementsByClassName('cover')[0]);