jQuery - 滚动停止时绑定事件 [英] jQuery - bind event on Scroll Stop
本文介绍了jQuery - 滚动停止时绑定事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我想在页面滚动时绑定一个事件,我可以使用 scroll();
.
If i want to bind an event on page scrolling i can use scroll();
.
但是如何在 scroll()
结束时触发?
But how to fire when scroll()
is ended up?
我想重现这个:
$(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"回调.
After 250 ms from the last scroll event, this will invoke the "scrollStopped" callback.
http://jsfiddle.net/wtRrV/256/
function onScrollStopped(domElement, callback) {
domElement.addEventListener('scroll', _.debounce(callback, 250));
}
function onScrollStopped(domElement, callback, timeout = 250) {
domElement.addEventListener('scroll', () => {
clearTimeout(callback.timeout);
callback.timeout = setTimeout(callback, timeout);
});
}
https://jsfiddle.net/kpsxdcv8/15/
clearTimeout 和 clearInterval 参数不必定义,甚至可以是错误类型甚至省略.
clearTimeout and clearInterval params don't have to be defined and can even be wrong types or even omitted.
这篇关于jQuery - 滚动停止时绑定事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文