スクロールしたらバーが付いてくるやつ

by kachibito

HTML

<div id="wrapper">

    <header>
        <h1>Simple Smart Sticky Navigation Bar</h1>
        
    </header>

    <nav>
        <p><a href="#">Sample navigation bar</a></p>
    </nav>
    
    <div id="content">
        <p>When you scrolls down the page, the red navigation bar will sticks at the top of the browser window and follows.</p>
        
    </div>

</div>

CSS

/* simple style reset */
body, h1, h2, h3, p {
    margin: 0; 
    padding: 0;
}

::selection {
    background: #c00;
    color:#fff;
}

::-moz-selection {
    background: #c00;
    color:#fff;
}

/* general styles */
body {
    background: url(img/bgnoise_lg.png);
    font: 20px/1.4 'Open Sans Condensed', Tahoma, Geneva, sans-serif;
}

a {
    color:#c00;
    text-decoration:none;
}

#wrapper {
    width:940px;
    margin: 0 auto;
}

header {
    text-align:center;
    padding:70px 0;
}

header h1 {
    color:#999;
    text-shadow:0 0 0 transparent, 0 1px 0 #fff, 0 -1px 0 #555;
    font-size:40px;
}

header h2 {
    display:inline-block;
    border: 1px dashed #999;
    padding: 2px 10px 5px;
    margin: 10px 0 0;
    border-radius: 5px;
    box-shadow: 0 1px 1px #fff;
    font-size:20px;
}

nav {
    background:url(img/nav-bg.png) no-repeat;
    height: 60px;
    width: 960px;
    margin-left: -10px;
    line-height:50px;
    position: relative;
}

nav:after {
    background:url(img/nav-shadow.png) top repeat-x;
    position: absolute;
    height:30px;
    width:940px;
    left:10px;
    top:60px;
    content:'';
}

nav p {
    padding: 0 70px;
}

nav a {
    color:#fff;
    text-shadow: 0 0 0 transparent, 0 -1px 1px #900;
}

#content {
    background: #fff;
    height: 1500px; /* presetting the height */
    -webkit-box-shadow: 0 0 5px rgba(0,0,0,0.3);
    box-shadow: 0 0 5px rgba(0,0,0,0.3);
}

#content p {
    padding:20px 60px;
}

.fixed {
    position:fixed;
}

JavaScript

$(document).ready(function() {
    
    //Calculate the height of <header>
    //Use outerHeight() instead of height() if have padding
    var aboveHeight = $('header').outerHeight();
    
    // when scroll
    $(window).scroll(function(){
        
        //if scrolled down more than the header's height
        if ($(window).scrollTop() > aboveHeight){
            
            // if yes, add "fixed" class to the <nav>
            // add padding top to the #content (value is same as the height of the nav)
            $('nav').addClass('fixed').css('top','0').next().css('padding-top','60px');
        } else {
            
            // when scroll up or less than aboveHeight, remove the "fixed" class, and the padding-top
            $('nav').removeClass('fixed').next().css('padding-top','0');
        }
    });
});