小编典典

用户停止滚动时的事件

javascript

当用户滚动页面时,我想做一些有趣的jQuery东西。但是我不知道如何解决这个问题,因为只有scroll()方法。

有任何想法吗?


阅读 501

收藏
2020-05-01

共1个答案

小编典典

您可以使scroll()每次用户滚动时都有一个超时被覆盖。这样,当他在一定毫秒后停止运行时,您的脚本将运行,但是如果他在此期间滚动,则计数器将重新开始,并且脚本将等待直到完成滚动为止。

更新:

因为这个问题又采取了一些行动,所以我认为我不妨使用添加scrollEnd事件的jQuery扩展对其进行更新。

// extension:

$.fn.scrollEnd = function(callback, timeout) {

  $(this).scroll(function(){

    var $this = $(this);

    if ($this.data('scrollTimeout')) {

      clearTimeout($this.data('scrollTimeout'));

    }

    $this.data('scrollTimeout', setTimeout(callback,timeout));

  });

};



// how to call it (with a 1000ms timeout):

$(window).scrollEnd(function(){

    alert('stopped scrolling');

}, 1000);


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<div style="height: 200vh">

  Long div

</div>
2020-05-01