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

参考: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);
        }
      }
    }
  };

上面版本有个问题,remove不能卸载事件.

滚轮事件在不同浏览器会有一点点区别,一个像Firefox使用DOMMouseScroll ,Firefox也可以使用addEventListener方法绑定DomMouseScroll事件,其他的浏览器滚轮事件使用mousewheel

修改版本后可以:

//Date:2020/12/03
componentDidMount() {
//在页面添加滚轮事件
    window.addEventListener("mousewheel", this.scrollFunc);
}
componentWillUnmount() {
    window.removeEventListener("mousewheel", this.scrollFunc);
}


scrollFunc = (e) => {
    let eva = e || window.Event;
    if (eva.wheelDelta) {
      //判断浏览器IE,谷歌滑轮事件
      if (eva.wheelDelta > 0) {
        //当滑轮向上滚动时
        //单次循环
        console.log("滑轮向上滚动");
      }
      if (eva.wheelDelta < 0) {
        //当滑轮向下滚动时
        console.log("滑轮向下滚动");
      }
    } else if (eva.detail) {
      //Firefox滑轮事件
      if (eva.detail > 0) {
        //当滑轮向上滚动时
        console.log("滑轮向上滚动");
      }
      if (eva.detail < 0) {
        //当滑轮向下滚动时
        console.log("滑轮向下滚动");
      }
    }
  };

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值