如果我想在页面滚动上绑定(bind)事件,我可以使用 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
});
有什么想法吗?
最佳答案
小型 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));
}
纯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 参数不必定义,甚至可以是错误的类型,甚至可以省略。
关于javascript - jQuery - 滚动停止上的绑定(bind)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14035083/