2014-11-22 70 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