擴展jquery scroll事件,支持 scroll start 和 scroll stop


效果預覽:

github:

https://besswang.github.io/webapp-scroll/

參考地址:

http://www.ghugo.com/special-scroll-events-for-jquery/

javascript里有一個事件是滾動事件,只要拖動滾動條,就會觸發事件。

用jquery的話,這個事件scroll 可以查看jquery api :http://api.jquery.com/scroll/

但scroll 事件有一個缺陷,就是只能判斷滾動條滾動,而不能監控滾動條停止滾動時的事件。

現用jquery擴展一下scroll 事件,新增

不多說,直接上代碼實在點。

(function(){
 
    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);
 
    special.scrollstart = {
        setup: function() {
 
            var timer,
                handler =  function(evt) {
 
                    var _self = this,
                        _args = arguments;
 
                    if (timer) {
                        clearTimeout(timer);
                    } else {
                        evt.type = 'scrollstart';
                        jQuery.event.handle.apply(_self, _args);
                    }
 
                    timer = setTimeout( function(){
                        timer = null;
                    }, special.scrollstop.latency);
 
                };
 
            jQuery(this).bind('scroll', handler).data(uid1, handler);
 
        },
        teardown: function(){
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid1) );
        }
    };
 
    special.scrollstop = {
        latency: 300,
        setup: function() {
 
            var timer,
                    handler = function(evt) {
 
                    var _self = this,
                        _args = arguments;
 
                    if (timer) {
                        clearTimeout(timer);
                    }
 
                    timer = setTimeout( function(){
 
                        timer = null;
                        evt.type = 'scrollstop';
                        jQuery.event.handle.apply(_self, _args);
 
                    }, special.scrollstop.latency);
 
                };
 
            jQuery(this).bind('scroll', handler).data(uid2, handler);
 
        },
        teardown: function() {
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid2) );
        }
    };
 
})();

可以將上面代碼保存到一個文件,這相當於一個插件,呵呵。調用方法如下:

(function(){
    jQuery(window).bind('scrollstart', function(){
        console.log("start");
    });
 
    jQuery(window).bind('scrollstop', function(e){
        console.log("end");
    });
 
})();

 

注意:如果是用高級版本的jquery(如1.9)的話需要將handle改為dispatch


免責聲明!

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



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