防止onScroll函数再次执行直到完成

时间:2014-03-18 20:24:02

标签: javascript jquery callback css-transitions

我在幻灯片中构建变体,当用户向上/向下滚动时幻灯片淡入/淡出。基本流程如下:

  1. 用户移动滚轮
  2. 使用$(window).on('DOMMouseScroll mousewheel')
  3. 检测移动
  4. 检测滚动是向上还是向下并跟踪滚动的数量
  5. 一旦滚动量达到任一方向的阈值,根据滚动方向显示上一张/下一张幻灯片
  6. 问题是在某些设备上,特别是触控板和魔法' mouses(触摸),onScroll函数执行几次。我希望该功能能够运行一次,完成,然后等待额外的onScroll事件再次运行。

    这是我的代码的简化版本。

    $(function() {
    
    
      var delta = 0;
      var wait = false;
      var scrollThreshold = 5;
    
      $(window).on('DOMMouseScroll mousewheel', function(e){  
    
        if (wait === false) {
    
          // If the scroll is up
          if (e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0) {
    
            // Track the amount of scroll
            delta = Math.min(0,delta - 1);
    
            if ( Math.abs(delta) >= scrollThreshold) {
    
    
              wait = true;
    
              // Go to the previous slide
              // This changes the class of the current and previous slides
              // causing several CSS transitions.
              $(active).removeClass('active');
              $(prev).addClass('active').removeClass('zoom');
    
              $(active, prev).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(e) {
    
                wait = false; 
                delta = 0;
    
              });
    
            }
    
          // If the scroll is down
          } else {
    
            // Track the amount of scroll
            delta = Math.max(0,delta + 1);
    
            if ( Math.abs(delta) >= scrollThreshold) {
    
              wait = true;
    
              // Go to the next slide
              // This changes the class of the current and next slides
              // causing several CSS transitions.
              $(active).addClass('zoom').removeClass('active');
              $(next).addClass('active');
    
              $(active, next).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(e) {      
    
                wait = false; 
                delta = 0;
    
              });
    
            }
    
          }
    
        }
    
      });
    

    问题是wait标志不会阻止该功能在触摸板上再次运行,并且“魔法”#39;鼠标。

    推荐使用该方法运行一次的方法是什么,然后在它收听新的滚动事件并再次运行之前等待它完成?

0 个答案:

没有答案