header gets smaller as you scroll - with the scrol

2019-09-05 13:08发布

问题:

There are plenty of tutorials to get a header's height to become smaller when you scroll down and get bigger when you scroll up past a certain point. I was wondering how to get the header's height to get smaller as soon as you scroll, but with the scroll. so if you stop scrolling before the animation is done, it stops as well...then when you resume scrolling up or down it resumes as well.

Here is a fiddle that doesnt work at all how I want but its the code I found to animate on scroll...

http://jsfiddle.net/A3XQG/

$(window).scroll(function(){ 

    var scrollPos = $(window).scrollTop();

    if( ( scrollPos === 0 ) && ( scrollState === 'top' ) ) {
        $('.header').stop().animate({height: '200px'}, 300);
        scrollState = 'scrolled';
    }       
    else if( ( scrollPos === 0 ) && ( scrollState === 'scrolled' ) ) {
        $('.header').stop().animate({height: '50px'}, 300);
        scrollState = 'top';
    }
});

回答1:

You're over-complicating it. Try this:

$(window).scroll(function(){ 
    $('.header').height(200 - (200 * $(this).scrollTop() / $('body').height()));
});

Demo: http://jsfiddle.net/9tgDs/

Update: (cap shrinkage at 150px)

$(window).scroll(function(){ 
    var _height = 200 - (200 * $(this).scrollTop() / $('body').height());

    if (_height >= 150) {
        $('.header').height(_height);
    }
});

Demo : http://jsfiddle.net/9tgDs/2/



标签: jquery scroll