简体   繁体   中英

Fixed navigation bar after scrolling

I am attempting to create a navigation bar that remains fixed only after it has reached the top of the page. I have the code working so that the nav is fixed, but I can't seem to get it to scroll to the top first.

Here's the HTML:

<div id= "home"> contentcontentcontent </div>
<div id="nav">
    <a href="#home">home</a>
    <a href="#gogreen">go green</a>
    <a href="#yourarea">your area</a>
    <a href="#howto">how to</a></div>

And the CSS:

nav {
text-align: center;
top: 600;
z-index: 100;
position: fixed;
width: 100%;
border: 0;
margin-bottom: 0;}

fixed {
top:600;
z-index: 100;
position: fixed;
width: 100%;}

home {
overflow: hidden;}

And the jQuery:

    $(document).ready(function() {
$(window).scroll(function () {
    //console log determines when nav is fixed
    console.log($(window).scrollTop())
    if ($(window).scrollTop() > 600) {
        $('#nav').addClass('fixed');
    }
    if ($(window).scrollTop() < 601) {
        $('#nav').removeClass('fixed');
    }
});

These were based off of responses to similar questions on this site, but nothing has seemed to work so far. Does anyone know what's wrong with my code?

When writing a CSS selector, ids and classes need to be prefixed by a # or a . respectively. In your CSS you have

nav { // rules }

fixed { // rules }

home { // rules }

When you should have

#nav { // rules }

.fixed { // rules }

#home { // rules }

Here is a fiddle of your code working.

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