header gets smaller as you scroll - with the scrol

2019-09-05 12:58发布

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';
    }
});

标签: jquery scroll
1条回答
趁早两清
2楼-- · 2019-09-05 13:42

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/

查看更多
登录 后发表回答