Debounce jquery scroll events

后端 未结 3 2035
夕颜
夕颜 2020-12-21 13:01

I just have a general question about debouncing. I have three menus at different positions on the page that when they reach a position 85px from the top of the window on scr

3条回答
  •  醉酒成梦
    2020-12-21 13:40

    For this case, I think it's really a matter of preference. Take a look at how the site responds in your given situation, and make adjustments if you feel the user experience is negatively affected. I tend to throttle/debounce scroll events.

    There are a few things you can do to speed up your scroll handlers (slightly). If you can use id's, for example, as in jQuery's guide to optimizing selectors, e.g. $('#myElement') is fast because it uses document.getElementById.

    More minor adjustments if you're worried about performance: Don't make any calls to adjust css if no call is needed. i.e. if nothing changed since the last time the scroll handler was fired. (See isFixed boolean)

    $(function(){
      var OFFSET = 85;
      var WAIT = 10;
    
      // Check the initial Position of the fixed_nav_container
      var stickyHeaderTop0 = $('.fixed_heading_shop').offset().top;
      var isFixed = false; // assuming that's the right default value
    
      $(window).scroll(_.throttle(function(){
        if($(window).scrollTop() > stickyHeaderTop0 - OFFSET) {
          if(!isFixed) {
            $('#fixed_heading_shop').css({position: 'fixed', top: OFFSET+'px'});
            $('#ghost_div0').css({display: 'block'});
            isFixed = true;
          }
        }
        else {
          if(isFixed) {
            $('#fixed_heading_shop').css({position: 'relative', top: '0px'});
            $('#ghost_div0').css({display: 'none'});
            isFixed = false;
          }
        }
      }, WAIT));
    });
    

    The only repeated call is $(window).scrollTop() and if you can combine all your scroll handlers (3?) then you would only need to make that call once per [throttled] scroll event.

提交回复
热议问题