How do I make my navbar change CSS class upon scro

2019-01-11 08:20发布

问题:

I'm using Bootstrap 3 and want to achieve this effect when the user scrolls past the large header image on my page. I need the background of the navbar to go from transparent to white. I looked in their code and I KNOW it is done with javascript, and even saw WHERE it was happening I think (look for the ID '#main-header' in that JS)...

Not knowing advanced Javascript aside, I'm looking for a way to apply this to my navigation bar when scrolling past a certain point. The class for my code is called 'navbar' and I would like it to turn white when it passes "#main". Let me know if you need more information, and thanks in advance if anyone wants to help!

回答1:

If you're using Twitter Bootstrap this can be achieved with the 'Affix' plugin

It's pretty straight forward to set up, here is the documentation



回答2:

The easiest way to accomplish what you're trying to do is a combination of some simple javascript (jQuery powered in this case) and CSS3 transitions.

We'll use JS to check for the windows scroll position on every scroll event and compare it to the distance of the bottom of the #main element - if the scroll position is greater, then we'll apply a class to the body to indicate we've scrolled past #main, and then we'll use CSS to define the nav styling for that "state."


So, our basic markup:

<nav class="nav">
    <a href="#" class="logo">[logo]</a>
</nav>
<div id="main">#main</div>
<div id="below-main">#below-main</div>

And our javascript:

// get the value of the bottom of the #main element by adding the offset of that element plus its height, set it as a variable
var mainbottom = $('#main').offset().top + $('#main').height();

// on scroll, 
$(window).on('scroll',function(){

    // we round here to reduce a little workload
    var stop = Math.round($(window).scrollTop());

    if (stop > mainbottom) {
        $('.nav').addClass('past-main');
    } else {
        $('.nav').removeClass('past-main');
    }

});

And, our styles:

.nav {
    background-color:transparent;
    color:#fff;
    transition: all 0.25s ease;
    position:fixed;
    top:0;
    width:100%;
    background-color:#ccc;
    padding:1em 0;
    /* make sure to add vendor prefixes here */
}

.nav.past-main {
    background-color:#fff;
    color:#444;
}

#main {
  height:500px;
  background-color:red;
}

#below-main {
  height:1000px;
  background-color:#eee;
}

A working example on Codepen

This is how I did it here. I also employ some scroll throttling and a bit more complicated styling semantics, but this is the gist of it.



回答3:

You could probably just use javascript element.scrollTop along with Jquery addClass and removeClass. Haven't tried it myself though.

Here's an overflow link for getting scrollbar position: How to get scrollbar position with Javascript?