jquery插件默認是不支持鼠標中輪滾輪事件的,現在我們可以用於添加跨瀏覽器的鼠標滾輪支持可以使用jquery的Mousewheel插件。
使用mousewheel事件有以下兩種方式:
使用mousewheel和unmousewheel事件函數;
使用經典的bind和unbind函數。
JavaScript Code復制內容到剪貼板
- $('div.mousewheel_example').mousewheel(fn);
- $('div.mousewheel_example').bind('mousewheel', fn);
mousewheel事件的處理函數有一點小小的變化,它除了第一個參數event外,還接收到第二個參數delta。通過參數delta可以獲取鼠標滾輪的方向和速度。如果delta的值是負的,那么滾輪就是向下滾動,正的就是向上。
以下是示例的源代碼:
JavaScript Code復制內容到剪貼板
- jQuery(function($) {
- $('div.mousewheel_example')
- .bind('mousewheel', function(event, delta) {
- var dir = delta > 0 ? 'Up' : 'Down',
- vel = Math.abs(delta);
- $(this).text(dir + ' at a velocity of ' + vel);
- return false;
- });
- });
jquery的鼠標滾輪插件 Mousewheel下載
使用
要使用這個功能,只需對目標元素的’mousewheel’事件綁定事件處理函數即可。
Mousewheel插件還提供了兩個事件函數:mousewheel和unmousewheel,可以對目標元素調用這兩個函數,並在參數中指定回調函數。
事件的回調函數第一個參數為event,第二個參數為delta,代表鼠標滾輪的變化值。
以下是上面兩種使用方式的示例:
JavaScript Code復制內容到剪貼板
- // 綁定方式
- $('#my_elem').bind('mousewheel', function(event, delta) {
- console.log(delta);
- });
- // 事件函數方式
- $('#my_elem').mousewheel(function(event, delta) {
- console.log(delta);
- }); 在發生滾輪滾動事件時,如果要設置屏幕滾動高度,就應該使用animate運動設置 scrollTop 來做。直接設置 window 的scrollTop不能達到效果。總會會出多點來。
-
$(window).on('mousewheel', function(event, delta) { //var direction = delta > 0 ? 'Up' : 'Down'; var step = $(window).height(); //可視區高度 var cur_top = $(window).scrollTop(); //當前滾過的高度 var direction = delta > 0 ? -1 : 1; var height = direction * step + cur_top; var x_height = Math.floor(height/step)*step; //滾過整數倍的可視區大小 $("html, body").stop().animate({ scrollTop: x_height }, 400); return false; });