【问题标题】:jQuery scroll event fire once per scroll每次滚动都会触发一次 jQuery 滚动事件
【发布时间】:2017-11-10 10:55:27
【问题描述】:

我有一些 jQuery 代码来检查我是否已经滚动到窗口底部。

$(window).scroll(function(){
    if($(window).scrollTop() + $(window).height() == $(document).height()) {
        appendToGrid();
    }
})

我的 appendToGrid() 函数将用户滚动到页面顶部并添加内容。问题是,我需要每个滚动调用一次这个函数。正如我现在所拥有的,每次滚动都会多次调用它。

如果我把它改成

$(window).one('scroll',function() {
    if($(window).scrollTop() + $(window).height() == $(document).height()) {
        appendToGrid();
    }
});

它总共只会触发一次,但我需要它在每次滚动时触发一次,以便用户可以滚动到底部并继续返回页面顶部。

我也尝试了以下方法,但它仍然会触发多次。

var fired = false;
$(window).scroll(function(){
    if($(window).scrollTop() + $(window).height() == $(document).height() && !fired) {
        fired = true;
        appendToGrid();
        fired = false;
    }
})

【问题讨论】:

    标签: javascript jquery scroll


    【解决方案1】:

    您可以在调用 appendToGrid 后添加一个冷却计时器。这类似于您的 fired 标志,但仅在等待 2000 毫秒后才会重置。您可以根据自己的感觉调整该时间。

    var recentScroll = false;
    $(window).on('scroll',function() {
        if(!recentScroll && $(window).scrollTop() + $(window).height() == $(document).height()) {
            appendToGrid();
            recentScroll = true;
            window.setTimeout(() => { recentScroll = false; }, 2000)
        }
    });
    

    【讨论】:

    • 只是好奇,因为你设置了超时,这会阻塞主线程吗?
    • Nope timeout 不会阻塞主线程,它不像其他语言的睡眠会暂停所有执行 - 它会继续执行其他操作,直到 2000 毫秒等待结束
    • 感谢您的快速响应和信息。很高兴知道!
    【解决方案2】:

    另一种选择是限制逻辑,使其仅在用户停止操作一段时间后发生。

    $(function(){
      //cache common variables so they are created once
      var $window = $(window);
      var $document = $(document);
      var debounce;
      
      $window.on('scroll', function(){
        //clear the delay if it's not finished yet
        if (debounce) clearTimeout(debounce);
        
        //start a new delay
        debounce = setTimeout(function(){
          //remove reference so another delay can start
          debounce = null;
          //perform whatever logic you normally would do
          if($window.scrollTop() + $window.height() == $document.height()) {
            appendToGrid();
          }
        }, 300);
      });
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多