1.Jquery-MouseWheel
jquery默認是不支持支持鼠標滾輪事件(mousewheel)
jquery MouseWheel下載:https://github.com/jquery/jquery-mousewheel/blob/master/jquery.mousewheel.js
然后就可以使用mousewheel和unmousewheel事件函數了
1 $('div.mousewheel_example').mousewheel(fn); 2 $('div.mousewheel_example').bind('mousewheel', fn);
Jquery MouseWheel兼容性
- FireFox瀏覽器使用DOMMouseScroll事件,其他(包括IE6)都是使用onmousewheel事件;
- FireFox中wheelDelta判斷滾動方向,其值為120/-120,為負數的時候表示向下滾動,整數的時候向上滾動
- 其他:detail(屬性)判斷方向,返回值是3的整數倍(3/-3), 為正數表示向上滾動,負數向下滾動
- opera:同時擁有wheelDelta和detail,其中“detail”屬性返回值和FF中的wheelDelta相同
使用實例
1 // jquery 兼容的滾輪事件
2 $(document).on("mousewheel DOMMouseScroll", function (e) {
3
4 var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) || // chrome & ie
5 (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1)); // firefox
6
7
8 if (delta > 0) { 9 // 向上滾 10 console.log("wheelup"); 11 } else if (delta < 0) { 12 // 向下滾 13 console.log("wheeldown"); 14 } 15 });
2.使用js原生實現滾輪事件
但是考慮到兼容性
IE下通過attachEvent實現事件監聽
Chrome和FF通過addEventListener來實現事件監聽
但是FF滾輪事件是:DOMAMouseSrcoll
其他瀏覽器:onmousewheel
事件監聽 | 滾輪事件 | |
Chrome | addEventListener | onmousewheel |
IE | attachEvent | onmousewheel |
FF | addEventListener | DOMAMouseSrcoll |
所以我自己封裝了一個兼容各瀏覽器的方法
1 addEvent: function(obj, xEvent, fn) { 2 if (obj.attachEvent) { 3 obj.attachEvent('on' + xEvent, fn); 4 } else { 5 obj.addEventListener(xEvent, fn, false); 6 } 7 },
調用:
1 this.addEvent($(document),"mousewheel",callback); //其他 2 this.addEvent($(document),"DOMMouseScroll",callback); //FF