這篇文章主要介紹了javascript實(shí)現(xiàn)禁止鼠標(biāo)滾輪事件的相關(guān)資料,需要的朋友可以參考下
平時(shí)我們兼容什么東西總是在調(diào)整低版本IE的兼容性,但是這回不是因?yàn)榈桶姹緸g覽器不給力。而是因?yàn)榛鸷o力過(guò)頭了,完全不顧其它瀏覽器的感受標(biāo)新立異了。除了火狐之外,所有的瀏覽器都可以使用MouseWheel事件來(lái)處理鼠標(biāo)滾輪的響應(yīng)。但是火狐卻偏偏不支持MouseWheel,而使用無(wú)厘頭的DOMMouseScroll,這玩意兒除了火狐以外其它瀏覽器都不兼容。也就是說(shuō),對(duì)于鼠標(biāo)滾輪事件的處理,火狐只能使用DOMMouseScroll。而非火狐則只能使用MouseWheel。這兩種事件實(shí)現(xiàn)的原理不同,他們處理的數(shù)據(jù)也不同。
- var firefox = navigator.userAgent.indexOf('Firefox') != -1;
- firefox ? img.addEventListener('DOMMouseScroll', MouseWheel, false) :
- (img.onmousewheel = MouseWheel);
- function MouseWheel(e) {
- e = e || window.event;
- if (e.stopPropagation) e.stopPropagation();
- else e.cancelBubble = true;
- if (e.preventDefault) e.preventDefault();
- else e.returnValue = false;
- }
我們來(lái)看個(gè)完整的代碼
- <!DOCTYPE html>
- <style>
- span {font:14px/20px 微軟雅黑;}
- #counter {
- width:50px;height:20px;
- border:1px solid #CCC;
- background:#F9F9F9;
- font:14px/20px Consolas;
- text-align:center;
- margin:10px;
- }
- </style>
- <span>使用鼠標(biāo)滾輪調(diào)整數(shù)值大小</span><br/>
- <div id="counter">0</div>
- <script>
- //判斷瀏覽器
- var isIE=navigator.userAgent.match(/MSIE (/d)/i);
- isIE=isIE?isIE[1]:undefined;
- var isFF=/FireFox/i.test(navigator.userAgent);
- //獲取元素
- var counter=document.getElementById("counter");
- //鼠標(biāo)滾輪事件
- if(isIE<9) //傳統(tǒng)瀏覽器使用MouseWheel事件
- counter.attachEvent("onmousewheel",function(){
- //計(jì)算鼠標(biāo)滾輪滾動(dòng)的距離
- //一格3行,每行40像素,所以除以120
- var v=event.wheelDelta/120;
- counter.innerHTML=counter.innerHTML*1+v;
- //阻止瀏覽器默認(rèn)方法
- return false;
- });
- else if(!isFF) //除火狐外的現(xiàn)代瀏覽器也使用MouseWheel事件
- counter.addEventListener("mousewheel",function(e){
- //計(jì)算鼠標(biāo)滾輪滾動(dòng)的距離
- var v=e.wheelDelta/120;
- counter.innerHTML=counter.innerHTML*1+v;
- //阻止瀏覽器默認(rèn)方法
- e.preventDefault();
- },false);
- else //奇葩的火狐使用DOMMouseScroll事件
- counter.addEventListener("DOMMouseScroll",function(e){
- //計(jì)算鼠標(biāo)滾輪滾動(dòng)的距離
- //一格是3行,但是要注意,這里和像素不同的是它是負(fù)值
- var v=-e.detail/3;
- counter.innerHTML=counter.innerHTML*1+v;
- //阻止瀏覽器默認(rèn)方法
- e.preventDefault();
- },false);
- </script>
以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。
新聞熱點(diǎn)
疑難解答
圖片精選