监听鼠标滚轮+控制只打印一次

参考:http://blog.sina.com.cn/s/blog_78106bb10101dgwp.html

let scrollNum = 0;
componentDidMount() {
//在页面添加滚轮事件
    window.onmousewheel = document.onmousewheel = this.scrollFunc;
    window.addEventListener("DOMMouseScroll", this.scrollFunc);
}
componentWillUnmount() {
    window.removeEventListener("DOMMouseScroll", this.scrollFunc);
}



scrollFunc = (e) => {
    let eva = e || window.Event;
    let type = Math.abs(scrollNum) % 2 === 0 ? true : false;
    if (eva.wheelDelta) {
      //判断浏览器IE,谷歌滑轮事件
      if (eva.wheelDelta > 0) {
        //当滑轮向上滚动时
        scrollNum -= 1;
        if (type) {
          //单次循环
          console.log("滑轮向上滚动", scrollNum);
        }
      }
      if (eva.wheelDelta < 0) {
        //当滑轮向下滚动时
        scrollNum += 1;
        if (type) {
          console.log("滑轮向下滚动", scrollNum);
        }
      }
    } else if (eva.detail) {
      //Firefox滑轮事件
      console.log("(e.detail======", eva.detail);

      if (eva.detail > 0) {
        //当滑轮向上滚动时
        scrollNum -= 1;
        if (type) {
          console.log("滑轮向上滚动", scrollNum);
        }
      }
      if (eva.detail < 0) {
        //当滑轮向下滚动时
        scrollNum += 1;
        if (type) {
          console.log("滑轮向下滚动", scrollNum);
        }
      }
    }
  };

你可能感兴趣的