简体   繁体   中英

How do I make the navigation bar of my site stay at the top when the viewer scrolls?

I am working on my website, and I want to have the the navigation bar stay at the top of the page when the user scrolls down. The main problem is that I want the header (appears above the navigation bar) to push the navigation bar down when the user scrolls to the top of the page. The HTML looks like this:

//this is the header (should scroll)
<p1 id="a"><a href="index.html" id="linkNoStyle">TITLE</a></p1>
<p1 id="b">SUBTITLE</p1>

//this div is the nav bar (should stay at top)
<div id="div">
    <a href="projects.html" id="link">PROJECTS</a>
    &nbsp;
    &nbsp;
    <a href="ideas.html" id="link">IDEAS</a>
    &nbsp;
    &nbsp;
    <a href="contact.html" id="link">CONTACT</a>
</div>

//this is also part of the nav bar (should stay at top)
<hr size="5" color=black>

the CSS looks like this:

#a{
    font-family:Futura;
    font-size:80pt;
    color:black;
}

#b{
    font-family:Futura;
    color:grey;
}

#div{
    padding-top:3px;
    padding-left:10px;
    font-family:Futura;
    background-color:#ff6600;
    color:white;
    height:25px;
}

Basically, I want the navigation bar to scroll up with the rest of the page, but when it reaches the top, it should stay there. Instructions on how to implement a solution into my code would be appreciated. Thanks.

There is a jQuery plugin that does it for you. It's called sticky . The official website here : http://stickyjs.com/

And the code here:

<script src="jquery.js"></script>
<script src="jquery.sticky.js"></script>
<script>
    $(document).ready(function(){
        $("#sticker").sticky({topSpacing:0});
    });
</script>

Hope this helps

You need to compare the offset().top of the element to the windows' current scrollTop . Try this:

var timer;
$(window).scroll(function() {
    var $div = $('#div');
    clearTimeout(timer);
    timer = setTimeout(function() {
        if ($div.offset().top < $(this).scrollTop()) {
            $div.addClass('fixed');
        }
        else {
            $div.removeClass('fixed');
        }
    }, 250);
});

Example fiddle

Note the scroll function fires once for every pixel scrolled, so the timer is there for performance reasons.

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