2014-11-22 3 views
0

500px 이하에서 특정 지점을지나 스크롤 할 때 클래스가 끈적 거리기 위해 탐색에 추가되는 동작을 활성화합니다. 내 코드는 다음과 같습니다.특정 화면 크기에서 스크롤 이벤트를 트리거하는 방법

$(window).on('scroll', function() { 
    var scrollTop = $(window).scrollTop(), 
    elementOffset = $('#query').offset().top, 
    distance = (elementOffset - scrollTop); 

     if(scrollTop > distance){ 
      $("#nav").addClass("sticky"); 
     } else { 
      $("#nav").removeClass("sticky"); 
     } 
}); 

브라우저 폭이 500px보다 큰 경우 모든 스크롤에서이 트리거링을 사용하지 마십시오. 이 이벤트가 500px 브라우저 너비를 초과하는 것을 차단하는 모범 사례는 무엇인가요?

임 추측은 단순하게 : 당신은 window.innerWidth (App.Utils.viewportWidth)에 대한 라이브 참조를 캐시 한 후 지속적으로 부울 값을 변경하는 흐름을 제어하는 ​​것을 사용할 필요가

if ($(window).width() < 500) { 
    //run above scroll function 
} 

답변

0

헤더 함수 (App.Header.watchHeader) 실행.

var App = window.App || {}; 

(function($) { 

    App.Utils = { 

    breakpointMobile: 500, 

    viewportWidth: null, 

    init: function() { 
     $(window).on('load', $.proxy(this.listenViewportResize, this));   
     $(window).on('resize', this.debounce($.proxy(this.listenViewportResize, this), 200, false)); 
    }, 

    // taken from underscore 
    debounce: function(func, wait, immediate) { 
     var timeout, args, context, timestamp, result; 
     return function() { 
     context = this; 
     args = arguments; 
     timestamp = new Date(); 
     var later = function() { 
      var last = (new Date()) - timestamp; 
      if (last < wait) { 
      timeout = setTimeout(later, wait - last); 
      } else { 
      timeout = null; 
      if (!immediate) result = func.apply(context, args); 
      } 
     }; 
     var callNow = immediate && !timeout; 
     if (!timeout) { 
      timeout = setTimeout(later, wait); 
     } 
     if (callNow) result = func.apply(context, args); 
     return result; 
     }; 
    }, 

    listenViewportResize: function() {  
     App.Utils.viewportWidth = window.innerWidth; 

     $(window).trigger('utils:viewportChanged'); 
    } 

    }; 

    $($.proxy(App.Utils.init, App.Utils)); 

}(jQuery)); 



(function($) { 

    App.Header = { 

    init: function() { 
     $(window).on('utils:viewportChanged', $.proxy(this.watchHeader, this)); 
    }, 

    watchHeader: function() { 
     if (App.Utils.viewportWidth < App.Utils.breakpointMobile + 'px') { 
     // do your mobile thing 
     } else { 
     // do your desktop thing 
     } 
    } 

    }; 

    $($.proxy(App.Header.init, App.Header)); 

}(jQuery)); 
+0

감사합니다. Elise. 나는이 일을 진행할 것이다. – JCHASE11

+0

구현에 적응해야하지만, 여기서 유일한 실제 복잡성은 window.innerWidth에 대한 동적 참조를 얻는 것이다. –

관련 문제