jquery 鼠標滾輪事件 插件 Mousewheel


 jquery插件默認是不支持鼠標中輪滾輪事件的,現在我們可以用於添加跨瀏覽器的鼠標滾輪支持可以使用jquery的Mousewheel插件。

 
使用mousewheel事件有以下兩種方式:
 
使用mousewheel和unmousewheel事件函數;
使用經典的bind和unbind函數。
 
JavaScript Code復制內容到剪貼板
  1. $('div.mousewheel_example').mousewheel(fn);  
  2. $('div.mousewheel_example').bind('mousewheel', fn);  
mousewheel事件的處理函數有一點小小的變化,它除了第一個參數event外,還接收到第二個參數delta。通過參數delta可以獲取鼠標滾輪的方向和速度。如果delta的值是負的,那么滾輪就是向下滾動,正的就是向上。
 
以下是示例的源代碼:
JavaScript Code復制內容到剪貼板
  1. jQuery(function($) {  
  2.     $('div.mousewheel_example')  
  3.         .bind('mousewheel', function(event, delta) {  
  4.             var dir = delta > 0 ? 'Up' : 'Down',  
  5.                 vel = Math.abs(delta);  
  6.             $(this).text(dir + ' at a velocity of ' + vel);  
  7.             return false;  
  8.         });  
  9. });  
jquery的鼠標滾輪插件 Mousewheel下載
 
使用
要使用這個功能,只需對目標元素的’mousewheel’事件綁定事件處理函數即可。
 
Mousewheel插件還提供了兩個事件函數:mousewheel和unmousewheel,可以對目標元素調用這兩個函數,並在參數中指定回調函數。
 
事件的回調函數第一個參數為event,第二個參數為delta,代表鼠標滾輪的變化值。
 
以下是上面兩種使用方式的示例:
 
JavaScript Code復制內容到剪貼板
  1. // 綁定方式  
  2. $('#my_elem').bind('mousewheel', function(event, delta) {  
  3.     console.log(delta);  
  4. });  
  5.   
  6. // 事件函數方式  
  7. $('#my_elem').mousewheel(function(event, delta) {  
  8.     console.log(delta);  
  9. });  

     

    在發生滾輪滾動事件時,如果要設置屏幕滾動高度,就應該使用animate運動設置 scrollTop 來做。直接設置 window 的scrollTop不能達到效果。總會會出多點來。
  10. $(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;  
        });

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM