2014-03-18 2 views
2

사용자가 위/아래로 스크롤 할 때 슬라이드가 페이드 인/아웃되는 슬라이드 쇼에 변형을 제작하고 있습니다.끝날 때까지 onScroll 함수가 다시 실행되지 않도록하십시오.

  1. 사용자는 스크롤이 위 또는 아래 인 경우 감지하고 스크롤 양을 한 번
  2. 스크롤 얼마나 많은 추적 $(window).on('DOMMouseScroll mousewheel')
  3. 와 움직임을 감지 자신의 스크롤 휠
  4. 이동 : 기본 과정은 이것이다 스크롤 방향에 따라 이전/다음 슬라이드 표시

문제는 일부 장치에서 특히 트랙 패드와 '마술'마우스 (tou ch)이면 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 플래그입니다.

함수를 한 번 실행하도록 권장하는 방법은 무엇입니까? 완료 될 때까지 기다렸다가 새로운 스크롤 이벤트를 수신하고 다시 실행하기 전에 어떻게해야합니까?

답변

0

underscorejs 라이브러리 (환상적)를 사용하는 경우 수행하려는 작업을 수행 할 _.debounce라는 기능이 있습니다.

여기에 함수 코드가 있습니다. 라이브러리에서 코멘트

// Returns a function, that, as long as it continues to be invoked, will not 
// be triggered. The function will be called after it stops being called for 
// N milliseconds. If `immediate` is passed, trigger the function on the 
// leading edge, instead of the trailing. 
_.debounce = function(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); 
    }; 
}; 

편집 :-) 완벽하게 설명 : 여기

var myEfficientFn = debounce(function() { 
    // All the taxing stuff you do 
}, 250); 

window.addEventListener('resize', myEfficientFn); 
+0

재미있는 자신의

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

사용 예제에 사용하려면이 기능을 리팩토링 David Walsh의 코드는 . 추가 JS 라이브러리없이 할 수 있다면 그 경로를 선호합니다. 나는 backburner에 이것을 유지할 것이다. –

+0

커스텀 jQuery'.debounce()'함수도 있지만, 본 적이있는 것은 시간에 기반하며 스크롤 량이 아닙니다. 불행히도. –

+0

다른 라이브러리를 포함하지 않고 자체적으로 사용할 수있는 함수가 포함되도록 업데이트했습니다. 근원은 데비드 Walsh에서이었다. – lommaj

관련 문제