如何防止多次触发滚动事件? [英] How to prevent multiple fires for scroll event?

查看:276
本文介绍了如何防止多次触发滚动事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试阻止多次滚动事件,例如250ms内只有一个事件。为此我在互联网上找到了以下的去抖功能。但我无法正常使用它。有什么问题?

I try to prevent multi times scroll event, e.g. only one event in 250ms. For this I found the debounce function below in Internet. But I couldn't use it properly. What is wrong?

function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};

// my code..
$(window).on('scroll', function (e) {

  debounce(function() {
    // The stuff below doesn't work.
    var scrollTop = $(window).scrollTop();
    if (scrollTop > 50) {
        $('.title').addClass('fixedPosition');
    } else {
        $('.title').removeClass('fixedPosition');
    }    
  }, 250);

});


推荐答案

由于函数 debounce 返回一个函数,你仍需要调用它:

Since the function debounce returns a function, you still need to call it:

$(window).on('scroll', function (e) {
    debounce(function() {
        var scrollTop = $(window).scrollTop();
        if (scrollTop > 50) {
            $('.title').addClass('fixedPosition');
        } else {
            $('.title').removeClass('fixedPosition');
        }    
    }()/*note the call here*/, 250);
});

这与将debounce逻辑包装在另一个函数中的功能不同,而函数 myLogic 将自动调用:

This is not the same as wrapping your debounce logic in another function whereas the function myLogic will be called automatically:

function myLogic(){
    var scrollTop = $(window).scrollTop();
    $('.title').toggleClass('fixedPosition', scrollTop > 50);
}

$(window).on('scroll', debounce(myLogic, 250));

这篇关于如何防止多次触发滚动事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆