简体   繁体   中英

DIV nav appear after scrolling past header

I am designing a site with a sticky nav appearing after scrolling past the header.

I got this to work using this script:

$(window).load(function(){
// Get the headers position from the top of the page, plus its own height
var startY = $('#header').position().top + $('#header').outerHeight();

$(window).scroll(function(){
    checkY();
 });

function checkY(){
    if( $(window).scrollTop() > startY ){
        $('#navbar').slideDown();
    }else{
        $('#navbar').slideUp();
    }
}

 // Do this on load just in case the user starts half way down the page
 checkY();
 });//]]>  

The problem is the scrip reads the height of my header on load, but because my header height is 100% of the viewport, when one resizes the window, the nav appears either too late or too early.

For example loading the page with a 670px high viewport, sized down to a 400px viewport. My header shrinks along to 400px high, even though te nav only appears after 670px

any way to fix this? thanks

Put your javascript function trigger in a document.ready() instead of a window.load() ?

Try moving this part OUT of the window.load().

$(window).scroll(function(){
    checkY();
 });

Try this:

$(window).on("load resize",function(e){
    // Get the headers position from the top of the page, plus its own height
    var startY = $('#header').position().top + $('#header').outerHeight();

    $(window).scroll(function(){
        checkY();
    });

    function checkY(){
        if( $(window).scrollTop() > startY ){
            $('#navbar').slideDown();
        }else{
            $('#navbar').slideUp();
        }
    }

    // Do this on load just in case the user starts half way down the page
    checkY();
});//]]>

It's only the first line (on load resize) that is modified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM