2013-03-07 2 views
12

"up"또는 "down"으로 사용자가 스크롤하는 방향을 감지해야합니다. 이 대답에있는 코드를 기반으로 : How can I determine the direction of a jQuery scroll event?jQuery/JavaScript : 스크롤 방향 감지 - 코드 구조 문제

저는 함수에서 랩핑하려 했으므로 좀 더 차별화되었습니다.하지만 불행히도 작동하지 않습니다. 나는 그것이 값을 반환하는 것과 관련이 있다고 생각하지만 방향은 항상 "위로"입니다. 자바 스크립트에 익숙하지 않아서이 문제를 해결하는 데 문제가 있습니다. 여기

코드입니다 :

$(document).ready(function() { 

    'use strict'; 

    var lastScrollTop = 0, 
     st, 
     direction; 

    function detectDirection() { 

     st = window.pageYOffset; 

     if (st > lastScrollTop) { 
      direction = "down"; 
     } else { 
      direction = "up"; 
     } 

     lastScrollTop = st; 

     return direction; 

    } 

    $(window).bind('scroll', function() { 

     detectDirection(); 
     console.log(detectDirection()); 

    }); 

}); 

그리고 나는 또한 Fiddle을 설정했습니다.

문제가있는 곳을 알려주십시오.

+0

함수와 변수 선언을 준비 함수 외부로 옮기는 것이 좋습니다. 이것이 문제를 해결할 지 확신 할 수는 없지만 한 번할만한 가치가있을 수 있습니다. –

+0

@AdamPlocher 팁 주셔서 감사합니다. 그러나 도움이되지 않았습니다. 그래도이 일을하는 데 일반적인 이점이 있습니까? 어쩌면 성능 현명한가? – Sven

답변

6
$(window).bind('scroll', function() { 

    var dir = detectDirection(); 
    console.log(dir); 

}); 

각 스크롤 이벤트 중에 detectDirection() 번을 두 번 호출했습니다. 첫 번째는 올바른 방향을 감지했지만 두 번째 것은 같은 장소에서 방금 보았으므로 "위로"돌아 왔고 그 점이 기록 된 것입니다.

+2

물론 아, 알았어! 고맙습니다! – Sven

2

이 함께 무엇을 얻을 참조 :

Barmar, 당신은 콘솔 출력 위의 라인 (전화)를 제거 할 수 언급 한 것 외에도
if (st > lastScrollTop) { 
    direction = "down"; 
} else if (st < lastScrollTop){ 
    direction = "up"; 
} else { 
    direction = "static"; 
} 

그냥 계속 :

console.log(detectDirection()); 
+1

네, 당신은 완전합니다.필자는 실제로 console.log (detectDirection());도 실제로는 * 함수를 호출한다는 것을 인식하지 못했습니다. – Sven

+1

그게 유일한 JS 실수라면 괜찮을거야;) – vol7ron

2
그것은 우리가 lastScrollTop를 업데이트하지 때문에 작동하지 않습니다와 같이

코드는 여기에 ... 작업 코드

$(function(config){ 
    var lastScrollTop = 0, // setting initial scrolltop as top of page 
     direction; // direction of scroll 1)up -1)down 0)static 

    function detectDirection() { 
     // current scrollTop can't be cached or in the local global scope 
     var st = window.pageYOffset; 

     if (st > lastScrollTop) { 
      // scrolling down 
      direction = -1; 
     } else if (st < lastScrollTop){ 
      // scrolling up 
      direction = 1; 
     } else { 
      // static 
      direction = 0; 
     } 

     // updated lastscrolltop with new current top 
     lastScrollTop = st; 

     // return the direction 
     return direction; 
    }` 

아래로 스크롤 할 때 정적/1을 위로 스크롤/-1로 사용했습니다.

누군가에게 도움이되기를 바랍니다.

0

BarMar의 대답으로 즉각적인 문제를 해결할 수 있지만 솔루션은 두 가지 작업을 수행 할 수 있도록 코드를 구조화하는 데 도움이되지 않기 때문에 새로운 대답을 제시하고 있습니다.

  1. 범위를 넓게 스크롤하면 다른 곳에서 해당 속성에 액세스 할 수 있습니다. 스크롤 위치가 특정 값이면 무언가를 할 수 있습니다.

  2. 스크롤링 성능을 향상시킵니다.

    // Your current functionality 
    $(document).ready(function() { 
        var scroll = { 
        down: true, 
        pos: 0 
        }; 
        var scrollPos; 
    
        var detectDirection = function() { 
        scrollPos = window.pageYOffset; 
    
        if (scrollPos > scroll.pos) { 
         scroll.down = true; 
        } else { 
         scroll.down = false; 
        } 
    
        scroll.pos = scrollPos; 
        }; 
    
        $(window).on('optimizedScroll', function() { 
        detectDirection(); 
    
        // Do something based on scroll direction 
        if (scroll.down == true) { 
         // fooFunction(); 
        } else { 
         // barFunction(); 
        } 
    
        // Do something based on scroll position, 
        // where scrollTrigger is a number 
        if (scroll.pos > scrollTrigger) { 
         // bazFunction(); 
        } 
        }); 
    }); 
    
    // Improve scroll performance 
    (function() { 
        var throttle = function(type, name, obj) { 
         var obj = obj || window; 
         var running = false; 
         var func = function() { 
         if (running) { 
          return; 
         } 
         running = true; 
         requestAnimationFrame(function() { 
         obj.dispatchEvent(new CustomEvent(name)); 
          running = false; 
         }); 
         }; 
         obj.addEventListener(type, func); 
        }; 
    
        throttle('scroll', 'optimizedScroll'); 
    })(); 
    

오히려) (.bind 사용하는 것보다, 당신은 jQuery .bind() documentation에 따라) (CSTE 연구진 사용해야합니다.

스크롤 성능을 향상시키는 Immediately Invoked Function Expression (IIFE)MDN documentation for the scroll event에서 비롯됩니다.