首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >jQuery -滚动停止时的绑定事件

jQuery -滚动停止时的绑定事件
EN

Stack Overflow用户
提问于 2012-12-26 09:05:57
回答 3查看 37K关注 0票数 19

如果我想在页面滚动上绑定一个事件,我可以使用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
    });

有什么想法吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-12-26 09:23:59

微小的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/

lodash (甚至更小)

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/

票数 46
EN

Stack Overflow用户

发布于 2012-12-26 09:23:24

您可以验证window.scrollY == 0是否

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

但此事件将在每次滚动时触发。

票数 0
EN

Stack Overflow用户

发布于 2014-09-10 09:17:46

我更喜欢能够收听某个事件。这就是我要做的:

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

    }($);

在这种情况下,window现在将触发scrollStop事件

$(window).scrollStopEventEmitter($);

现在我可以在scrollStop上收听了

$(window).on('scrollStop',function(){
        // code
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14035083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档