参考: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("滑轮向下滚动");
}
}
};