2014-11-22 80 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寬時,我不希望在每次滾動時都觸發此功能。限制該事件觸發高於500像素的瀏覽器寬度的最佳做法是什麼?

即時猜測它的那樣簡單:

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

回答

0

需要緩存的實時參考window.innerWidth(App.Utils.viewportWidth),然後使用不斷變化值作爲一個布爾值來控制流量執行你的頭函數(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 2014-11-22 04:00:36

+0

你必須適應你的實現,但這裏唯一真正的複雜性是實現對window.innerWidth的動態引用 – 2014-11-22 04:02:10