如果我想在页面滚动上绑定一个事件,我可以使用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
});
有什么想法吗?
发布于 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));
}
纯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参数不必定义,甚至可以是错误的类型,甚至可以省略。
发布于 2012-12-26 09:23:24
您可以验证window.scrollY == 0
是否
$(window).scroll(function(){
if (window.scrollY == 0) {
//...
}
});
但此事件将在每次滚动时触发。
发布于 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
https://stackoverflow.com/questions/14035083
复制相似问题