简体   繁体   中英

Javascript Fixed Navigation Bar Jumping

I've been playing around with a fixed navigation bar, but I've noticed that when it "fixes" itself, the content below all jumps up on the page. This is the JSFiddle I've been working on , if you look closely you'll notice that when the nav bar becomes fixed to the top of the screen, the content jumps up ~1 line. I've tried playing around with the Javascript:

 var win      = $(window),
    fxel     = $('nav'),
    eloffset = fxel.offset().top;


win.scroll(function() {
    if (eloffset < win.scrollTop()) {
        fxel.addClass("fixed");
    } else {
        fxel.removeClass("fixed");
    }
});

but I'm fairly certain the problem is in the CSS:

    *{
    margin: 0;
    padding: 0;
}

nav {
    width: 100%;
    background: white;
    height: 35px;
    border-bottom: solid 1px #E8E8E8;
}

nav.fixed {
  position:fixed;
  top: 0;
  right:0px;
  left:0px;
  z-index:999;
  height: 30px;
  border-bottom: solid 1px #E8E8E8;
  padding-bottom: 5px;
}

h1{
    font-family: 'Lobster', cursive;
    font-size: 50px;
    text-align: center;
}

Any solutions on how to fix the jumping would be really helpful.

For refrence, I'm trying to get something sort of like this where the very top of the page isn't part of the navbar.

When an element is set to position: fixed , it no longer takes up space on the page, meaning it won't push other elements down on the page. So as soon as your javascript adds the fixed class, the element no longer takes up space, and so the other content jumps up to take the place where it was.

To offset this, you may need to add another rule to add something like a top margin to the next element. The top margin will need to be the height of the (now) fixed element, plus any padding and margin in the fixed element:

https://jsfiddle.net/h6g33wne/8/

nav.fixed + * {
  margin-top: 35px;
}

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