Debounce jquery scroll events

后端 未结 3 2038
夕颜
夕颜 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:52

    Without making any changes in HTML mark up, you can optimize your code a little:

    $(function(){
    // Check the initial Position of the fixed_nav_container
     var stickyHeaderTop0 = $('.fixed_heading_shop').offset().top;
     var stickyHeaderTop1 = $('.fixed_heading_pricetable').offset().top;
     var stickyHeaderTop2 = $('.fixed_heading_layout').offset().top;
     $(window).scroll(function(){
            if( $(window).scrollTop() > stickyHeaderTop0-85) {
                    $('.fixed_heading_shop').css({position: 'fixed', top: '85px'});  
                    $('.ghost_div0').css({display: 'block'});
            } else {
                    $('.fixed_heading_shop').css({position: 'relative', top: '0px'});
                    $('.ghost_div0').css({display: 'none'});
            }
            if( $(window).scrollTop() > stickyHeaderTop1-85 ) {
                    $('.fixed_heading_pricetable').css({position: 'fixed', top: '85px'});  
                    $('.ghost_div1').css({display: 'block'});       
            } else {
                    $('.fixed_heading_pricetable').css({position: 'relative', top: '0px'});
                    $('.ghost_div1').css({display: 'none'});    
            }
            if( $(window).scrollTop() > stickyHeaderTop2-85) {
                    $('.fixed_heading_layout').css({position: 'fixed', top: '85px'});  
                    $('.ghost_div2').css({display: 'block'});
            } else {
                    $('.fixed_heading_layout').css({position: 'relative', top: '0px'});
                    $('.ghost_div2').css({display: 'none'});
            }
     });
    });
    

    And if you give a common class to the three elements for which the if..else functionality is same, then it will be more optimized. I am adding a class 'common' here in JS, you can add it in html itself.

    $(function(){
    // add common class to elements
     $('.fixed_heading_shop, .fixed_heading_pricetable, .fixed_heading_layout').addClass('common');
     var elemArr = [];
     // Check the initial Position of the fixed_nav_container
     $('.common').each(function(index){
            elemArr.push($(this).offset().top);
     })
     $(window).scroll(function(){
         $('.common').each(function(index){
            if( $(window).scrollTop() > elemArr[index]) {
                    $(this).css({position: 'fixed', top: '85px'});  
                    $('.ghost_div'+index).css({display: 'block'});
            } else {
                    $(this).css({position: 'relative', top: '0px'});
                    $('.ghost_div'+index).css({display: 'none'});
            }
         });
     });
    });
    

提交回复
热议问题