jQuery - Sticky header that shrinks when scrolling down

前端 未结 6 1570
礼貌的吻别
礼貌的吻别 2020-11-28 00:58

I wonder how to make a sticky header shrink(with animation) when you scroll down the page and goes back to normal state when the page is scrolled up to the top. Here are two

6条回答
  •  心在旅途
    2020-11-28 01:28

    I did an upgraded version of jezzipin's answer (and I'm animating padding top instead of height but you still get the point.

     /**
     * ResizeHeaderOnScroll
     *
     * @constructor
     */
    var ResizeHeaderOnScroll = function()
    {
        this.protocol           = window.location.protocol;
        this.domain             = window.location.host;
    };
    
    ResizeHeaderOnScroll.prototype.init    = function()
    {
        if($(document).scrollTop() > 0)
        {
            $('header').data('size','big');
        } else {
            $('header').data('size','small');
        }
    
        ResizeHeaderOnScroll.prototype.checkScrolling();
    
        $(window).scroll(function(){
            ResizeHeaderOnScroll.prototype.checkScrolling();
        });
    };
    
    ResizeHeaderOnScroll.prototype.checkScrolling    = function()
    {
        if($(document).scrollTop() > 0)
        {
            if($('header').data('size') == 'big')
            {
                $('header').data('size','small');
                $('header').stop().animate({
                    paddingTop:'1em',
                    paddingBottom:'1em'
                },200);
            }
        }
        else
          {
            if($('header').data('size') == 'small')
            {
                $('header').data('size','big');
                $('header').stop().animate({
                    paddingTop:'3em'
                },200);
            }  
          }
    }
    
    $(document).ready(function(){
        var resizeHeaderOnScroll = new ResizeHeaderOnScroll();
        resizeHeaderOnScroll.init()
    })
    

提交回复
热议问题