简体   繁体   中英

Fixed Navigation Bar with two different states

What I want to do is have a fixed navigation bar that is 10px from the top of the window unless it is within the first 200px of the document, then I want it to be 200px from the top ...

So basically I want a navigation bar that is 200px from the top to start off with, but when the user scrolls down 190px the navigation bar scrolls, staying always 10px from the top of the window.

You first listen to the scroll event of the window, and then use the scroll value to know what state to apply to you element. Example with jQuery :

var fixed = false, limit = 50;
$(window).scroll(function()
{
    if (window.scrollTop < 50 && fixed)
    {
        $("#header").css({ position: "relative" });
        fixed = false;
    }
    else if (window.scrollTop > 50 && !fixed)
    {
        $("#header").css({ position: "fixed" });
        fixed = true;
    }
});

Also related to this post for code example

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