今天尝试写基于jquery的滚动条,遇到了滚轮事件的兼容性问题,在firefox下和在IE下以及其它浏览器下,监听的事件有区别,查了下相关资料总结一下不同浏览器下鼠标滚轮事件兼容性的处理方式:
在 firefox 下 需要监听 DOMMouseScroll,即:
if(window.addEventListener){
/**DOMMouseScrollisformozilla.*/
window.addEventListener('DOMMouseScroll',wheel,false);
}
在IE或其它浏览器下,这样添加监听就可以了:
window.onmousewheel=document.onmousewheel=wheel;
/**
*CreatedbyAdministratoron/7/15.
*/
/**Eventhandlerformousewheelevent.
*鼠标滚动事件
*/
$(function(){
varwheel=function(event){
vardelta=0;
if(!event)/*ForIE.*/
event=window.event;
if(event.wheelDelta){/*IE/Opera.*/
delta=event.wheelDelta/120;
}elseif(event.detail){
/**Mozillacase.*/
/**InMozilla,signofdeltaisdifferentthaninIE.
*Also,deltaismultipleof3.
*/
delta=-event.detail/3;
}
/**Ifdeltaisnonzero,handleit.
*Basically,deltaisnowpositiveifwheelwasscrolledup,
*andnegative,ifwheelwasscrolleddown.
*/
if(delta)
handle(delta);
/**Preventdefaultactionscausedbymousewheel.
*Thatmightbeugly,butwehandlescrollssomehow
*anyway,sodon'tbotherhere..
*/
if(event.preventDefault)
event.preventDefault();
event.returnValue=false;
}
/**Initializationcode.
*Ifyouuseyourowneventmanagementcode,changeitasrequired.
*/
if(window.addEventListener){
/**DOMMouseScrollisformozilla.*/
window.addEventListener('DOMMouseScroll',wheel,false);
}
/**IE/Opera.*/
window.onmousewheel=document.onmousewheel=wheel;
/**Thisishigh-levelfunction.
*Itmustreacttodeltabeingmore/lessthanzero.
*/
varhandle=function(delta){
varrandom_num=Math.floor((Math.random()*100)+50);
if(delta
//alert("鼠标滑轮向下滚动:"+delta+"次!");//1
$("#mScroll").val("鼠标滑轮向下滚动:"+delta+"次!");
return;
}else{
//alert("鼠标滑轮向上滚动:"+delta+"次!");//-1
$("#mScroll").val("鼠标滑轮向上滚动:"+delta+"次!");
return;
}
}
})
如果觉得《HTML 鼠标绑定滚动条 js鼠标滑轮滚动事件绑定(兼容主流浏览器)》对你有帮助,请点赞、收藏,并留下你的观点哦!