用户停止滚动时的事件

dan*_*ntz 54 javascript jquery scroll javascript-events

当用户滚动页面时,我想做一些花哨的jQuery东西.但我不知道如何解决这个问题,因为只有scroll()方法.

有任何想法吗?

Ste*_*ler 70

你可以让scroll()每次用户滚动时都会被覆盖超时.这样,当他在一定程度的毫秒后停止运行脚本时,但如果他在此期间滚动计数器将重新开始,脚本将等待直到他再次完成滚动.

更新:

因为这个问题再次得到了一些动作,我想我也可以用添加scrollEnd事件的jQuery扩展来更新它

// extension:
$.fn.scrollEnd = function(callback, timeout) {          
  $(this).scroll(function(){
    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback,timeout));
  });
};

// how to call it (with a 1000ms timeout):
$(window).scrollEnd(function(){
    alert('stopped scrolling');
}, 1000);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="height: 200vh">
  Long div
</div>
Run Code Online (Sandbox Code Playgroud)

  • 该技术也称为事件去抖动。 (5认同)
  • 1000毫秒是一个很长的时间好250左右 (4认同)

Phi*_*l M 60

下面是一个使用setTimeout在用户停止滚动时触发函数的简单示例:

(function() {        
    var timer;
    $(window).bind('scroll',function () {
        clearTimeout(timer);
        timer = setTimeout( refresh , 150 );
    });
    var refresh = function () { 
        // do stuff
        console.log('Stopped Scrolling'); 
    };
})();
Run Code Online (Sandbox Code Playgroud)

在滚动事件触发时清除计时器.滚动停止后,将触发刷新功能.

或者作为插件:

$.fn.afterwards = function (event, callback, timeout) {
    var self = $(this), delay = timeout || 16;

    self.each(function () { 
        var $t = $(this);
        $t.on(event, function(){
            if ($t.data(event+'-timeout')) {
                clearTimeout($t.data(event+'-timeout'));
            }
            $t.data(event + '-timeout', setTimeout(function () { callback.apply($t); },delay));
        })
    });
    return this;
};
Run Code Online (Sandbox Code Playgroud)

在div(带命名空间)上的最后一个滚动事件的100ms之后触发回调:

$('div.mydiv').afterwards('scroll.mynamespace', function(e) {
        // do stuff when stops scrolling
        $(this).addClass('stopped');
    }, 100
);
Run Code Online (Sandbox Code Playgroud)

我用它来滚动和调整大小.

  • 这被称为"去抖动"方法.更多信息(和可重复使用的功能):http://davidwalsh.name/function-debounce (2认同)

小智 10

这是另一个基于提到的相同想法的更通用的解决方案:

var delayedExec = function(after, fn) {
    var timer;
    return function() {
        timer && clearTimeout(timer);
        timer = setTimeout(fn, after);
    };
};

var scrollStopper = delayedExec(500, function() {
    console.log('stopped it');
});

document.getElementById('box').addEventListener('scroll', scrollStopper);
Run Code Online (Sandbox Code Playgroud)