如何在特定屏幕尺寸上触发滚动事件

时间:2014-11-22 03:12:01

标签: javascript jquery

宽度低于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浏览器宽度的最佳做法是什么?

我猜它很简单:

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

1 个答案:

答案 0 :(得分: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));