Подтвердить что ты не робот

JQuery - связать событие в режиме прокрутки

Если я хочу связать событие на прокрутке страницы, я могу использовать scroll();.

Но как срабатывать, когда заканчивается scroll()?

Я хотел бы воспроизвести это:

   $(window).scroll(function(){
    //do somenthing
    });

    $(window).scrollSTOPPED(function(){  //--> when i'm scrolling then i stop to scrolling (so NOT when page scrollbar is at the end top or bottom :)
    //do somenthing else
    });

любые идеи?

4b9b3361

Ответ 1

крошечный способ JQuery

$.fn.scrollStopped = function(callback) {
  var that = this, $this = $(that);
  $this.scroll(function(ev) {
    clearTimeout($this.data('scrollTimeout'));
    $this.data('scrollTimeout', setTimeout(callback.bind(that), 250, ev));
  });
};

Через 250 мс после последнего события прокрутки это вызовет обратный вызов scrollStopped.

http://jsfiddle.net/wtRrV/256/

Лодаш (еще меньше)

function onScrollStopped(domElement, callback) {
  domElement.addEventListener('scroll', _.debounce(callback, 250));
}

http://jsfiddle.net/hotw1o2j/

чистый JS (технически самый маленький)

function onScrollStopped(domElement, callback, timeout = 250) {
  domElement.addEventListener('scroll', () => {
    clearTimeout(callback.timeout);
    callback.timeout = setTimeout(callback, timeout);
  });
}

https://jsfiddle.net/kpsxdcv8/15/

странный факт

Параметры clearTimeout и clearInterval не должны быть определены и могут даже быть неправильными типами или даже опущены.

http://jsfiddle.net/2w5zLwvx/

Ответ 2

само событие не существует, поскольку прокрутка - это одно событие, которое запускается каждый раз, когда пользователь прокручивается с определенным шагом.

Однако вы можете эмулировать событие.

Кредит Джеймсу Падольси за это, снятый с его веб-страницы:. Прочтите его здесь, чтобы полностью понять код и как он реализован.

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

(функция() {

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

Возможно, стоит отметить, что есть несколько вопросов, связанных с вашими, так что это может быть возможное дублирование. например Javascript: выполните действие после прокрутки пользователя  и Событие пожара после прокрутки полос прокрутки или колесика мыши с помощью javascript

Ответ 3

Вы можете проверить, если window.scrollY == 0

$(window).scroll(function(){
  if (window.scrollY == 0) {
    //...
  }
});

Но это событие будет запущено в каждом прокрутке.

Ответ 4

Я предпочитаю прослушивать событие. Это то, что я делаю:

Плагин jquery:

+function(jQuery){
        var scrollStopEventEmitter = function(element, jQuery) {
            this.scrollTimeOut = false;
            this.element       = element;
            jQuery(element).on('scroll', $.proxy(this.onScroll, this));
        }

        scrollStopEventEmitter.prototype.onScroll = function() 
        {
            if (this.scrollTimeOut != false) {
              clearTimeout(this.scrollTimeOut);
            }

            var context = this;

            this.scrollTimeOut = setTimeout(function(){ context.onScrollStop()}, 250);
        }

        scrollStopEventEmitter.prototype.onScrollStop = function() 
        {
            this.element.trigger('scrollStop');
        }

        jQuery.fn.scrollStopEventEmitter = function(jQuery) {   
            return new scrollStopEventEmitter(this, jQuery);
        };

    }($);

В этом случае окно теперь вызывает событие scrollStop

$(window).scrollStopEventEmitter($);

Теперь я могу прослушивать scrollStop

$(window).on('scrollStop',function(){
        // code