3 回答

TA貢獻(xiàn)1744條經(jīng)驗 獲得超4個贊
下面是一個使用setTimeout在用戶停止?jié)L動時觸發(fā)函數(shù)的簡單示例:
(function() {
var timer;
$(window).bind('scroll',function () {
clearTimeout(timer);
timer = setTimeout( refresh , 150 );
});
var refresh = function () {
// do stuff
console.log('Stopped Scrolling');
};
})();
在滾動事件觸發(fā)時清除計時器。滾動停止后,將觸發(fā)刷新功能。
或者作為插件:
$.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;
};
在div(帶命名空間)上的最后一個滾動事件的100ms之后觸發(fā)回調(diào):
$('div.mydiv').afterwards('scroll.mynamespace', function(e) {
// do stuff when stops scrolling
$(this).addClass('stopped');
}, 100
);
我用它來滾動和調(diào)整大小。

TA貢獻(xiàn)1829條經(jīng)驗 獲得超9個贊
這是另一個基于提到的相同想法的更通用的解決方案:
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);
添加回答
舉報