减少滚动事件的延迟

Jim*_*mmy 3 javascript jquery

这是我当前的代码:http : //jsfiddle.net/spadez/9sLGe/3/

我担心这样做会非常滞后,因为它正在监视scroll. 我在另一个关于去抖动的问题中看到了这样的提及:

var scrollTimeout,
    callback = function () {  
        /// Do your things here
    };

$(window).scroll(function () {

    if (scrollTimeout)
        clearTimeout(scrollTimeout);

    scrollTimeout = setTimeout(callback, 40);

});
Run Code Online (Sandbox Code Playgroud)

谁能告诉我这是否是一个好主意以及如何整合它。

詹姆士

Jos*_*son 5

为了获得流畅的结果,我会坚持在每个滚动事件上触发。否则在粘或不粘之前会有延迟。

但是,您可以通过缓存 jQuery 集合来提高函数的性能,并且仅在需要时才粘贴/取消粘贴。

这是一个使用您的代码的简单示例模块:http : //jsfiddle.net/9sLGe/9/

(function() {
  var $select = $('#select');
  var $window = $(window);
  var isFixed = false;
  var init = $('#select').offset().top;

  $window.scroll(function() {
    var currentScrollTop = $window.scrollTop();
    if (currentScrollTop > init && isFixed === false) {
      isFixed = true;
      $select.css({
        top: 0,
        position: 'fixed'
      });
      console.log("fixed");
    } else if (currentScrollTop <= init && isFixed === true) {
      isFixed = false;
      $select.css('position', 'relative');
      console.log("unfixed");
    }
  });
}());
Run Code Online (Sandbox Code Playgroud)