jQuery - bind event on Scroll Stop

前端 未结 4 2075
生来不讨喜
生来不讨喜 2020-12-01 03:07

If i want to bind an event on page scrolling i can use scroll();.

But how to fire when scroll() is ended up?

I would like to reprod

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 03:48

    the event itself doesn't exist as scroll is a single event fired everytime the user scrolls by a certain increment.

    What you can do however is emulate the event.

    Credit to James Padolsey for this, lifted from his webpage:. Read it here to fully understand the code and how it is implemented.

    http://james.padolsey.com/javascript/special-scroll-events-for-jquery/

    (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) );
        }
    };   })();
    

    Probably worth noting that there are several questions related to yours, so this may be a possible duplication. e.g. Javascript: do an action after user is done scrolling and Fire event after scrollling scrollbars or mousewheel with javascript

提交回复
热议问题