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

谁都会走 提交于 2019-12-13 04:54:52

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/20019661/how-do-i-make-the-navigation-bar-of-my-site-stay-at-the-top-when-the-viewer-scro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!