var wheel = function(event) { var delta = 0; console.log(event); if (!event) /* For IE. */ event = window.event; if (event.wheelDelta) { /* IE/Opera/Chrome. 鼠标向上滑 120*/ delta = event.wheelDelta / 120; } else if (event.detail) { /** Mozilla case. */ /** In Mozilla, sign of delta is different than in IE. * Also, delta is multiple of 3. 鼠标向上滑为 -3 为了统一正负号(方向) */ delta = -event.detail / 3; } /** If delta is nonzero, handle it. * Basically, delta is now positive if wheel was scrolled up, * and negative, if wheel was scrolled down. */ if (delta) handle(delta); /** Prevent default actions caused by mouse wheel. * That might be ugly, but we handle scrolls somehow * anyway, so don‘t bother here.. */ if (event.preventDefault) event.preventDefault(); event.returnValue = false; } /** Initialization code. * If you use your own event management code, change it as required. */ if (window.addEventListener) { /** DOMMouseScroll is for mozilla. */ window.addEventListener(‘DOMMouseScroll‘, wheel, false); } /** IE/Opera. */ window.onmousewheel = document.onmousewheel = wheel; /** This is high-level function. * It must react to delta being more/less than zero. */ var handle = function(delta) { if (delta < 0) { alert("鼠标滑轮向下滚动:" + delta + "次!"); // 1 return; } else { alert("鼠标滑轮向上滚动:" + delta + "次!"); // -1 return; } }
function mousewheel(ev){ var oEvent=ev||event; var dir=true; if(oEvent.wheelDelta){ console.log("wheelDelta:"+oEvent.wheelDelta); dir=oEvent.wheelDelta>0?true:false; //向上滚动为120 //向下滚动为-120 }else{ //火狐的event.detail向下滑为正数,值与其他浏览器相反 console.log("detail:"+oEvent.wheelDelta); dir=oEvent.detail<0?true:false; //向上滚动为-3 //向下滚动为3 } //根据手表方向设定具体业务逻辑 if(dir){ oBox.style.height=oBox.offsetHeight-10+‘px‘; }else{ oBox.style.height=oBox.offsetHeight+10+‘px‘; } // addEventLisrener 绑定的时间需要通过event对象下面的的 preventDefaul if(oEvent.preventDefault){ oEvent.preventDefault(); } return false;//阻止默认行为(阻止的是 obj.on时间名称=fn 所触发的默认行为) } //添加事件 ie chrome document.onmousewheel=mousewheel; if(document.addEventListener){ //火狐 chrome document.addEventListener(‘DOMMouseScroll‘,mousewheel,false); }
时间: 2024-10-26 15:36:35