Header changes as you scroll down (jQuery)

后端 未结 7 1519
滥情空心
滥情空心 2020-12-01 01:22

TechCrunch recently redesigned their site and they have a sweet header that minifies into a thinner version of their branding as you scroll down.

You can see what I

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 02:17

    Old question but I recently ran into this problem and the accepted solution on here wouldnt work because the height of my div's weren't fixed, so in short here is the solution I came across.

    JSfiddle: http://jsfiddle.net/Lighty_46/27f4k/12/

    $(document).ready(function () {
    
    var bluebutton = $('#blue_link').offset().top - parseFloat($('#blue_link').css('marginBottom').replace(/auto/, 0));
    
    var bluebuttonbottom = $('#blue_block_bottom').offset().top - $('#main_nav').height() - parseFloat($('#blue_link').css('marginBottom').replace(/auto/, 0));
    
    $(window).scroll(function (event) {
        // what the y position of the scroll is
            var y = $(this).scrollTop();
    
        // whether that's below the top of the div
            if (y >= bluebutton) {
    
        // if so, ad the fixed class
            $('.home_nav').addClass('blue_selected');
    
    }
    
        // whether you have passed the bottom of the div
            if (y >= bluebuttonbottom) {
    
        // if so remove the selected class
            $('.home_nav').removeClass('blue_selected');
    
            } else {
    
        // otherwise remove it
            $('.home_nav').removeClass('blue_selected');
    }
    
    });
    });
    

    SO basically,

    • $('#blue_link') was the top div I wanted to to trigger the class change
    • $('#blue_block_bottom') was the div I wanted to to trigger the class removal
    • $('#main_nav') was my fixed header

    So when the bottom of my header reaches the top of the div, the class "blue_selected" is applied to ".home_nav" ..... then if the bottom of the div passes the bottom of the header the class "blue_selected" is removed from ".home_nav".

    You will need to repeat this for each of your buttons with their respective div's

    I have tested it in Chrome, Firefox and IE 10 to 8 (works in 8 but the fiddle breaks slightly).

    Hope this helps, it probably isn't the best way to do it in all honesty and it probably has some errors in there somewhere but it was the only one I got working.

提交回复
热议问题