javascript - jQuery - 滚动停止上的绑定(bind)事件

标签 javascript jquery scroll

如果我想在页面滚动上绑定(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));
}

http://jsfiddle.net/hotw1o2j/

纯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 参数不必定义,甚至可以是错误的类型,甚至可以省略。

http://jsfiddle.net/2w5zLwvx/

关于javascript - jQuery - 滚动停止上的绑定(bind)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14035083/

相关文章:

javascript - Firefox 扩展打开一个 HTML 选项页面

javascript - JavaScript中如何通过类名获取值?

javascript - 尝试将 10 添加到 this.y 变量,但返回 NaN

Javascript:通过将路径作为字符串传递给对象来从对象中获取深层值(value)

javascript - 如何在 Heroku 上部署 Actions-On-Google?

javascript - Angular.JS - 添加 Controller 时出错

javascript - js数+1问题

xcode - 如何解决UITableView中的缓慢滚动-使用YouTube API

css - 相对于滚动区域的位置

javascript - 在Cesium中禁用鼠标滚轮