Navbar active tab change color when scrolled

2019-06-14 10:28发布

问题:

I would like my active tab to change colour when user scroll pass 1000px and return to original color when it's <1000px.

I've tried the CSS below which works and changes the background on active tab permanently.

.navbar-default .navbar-nav > .active{
   background: #111;
}

.navbar-default .navbar-nav > .active > a, 
.navbar-default .navbar-nav > .active > a:hover, 
.navbar-default .navbar-nav > .active > a:focus {
    background: #111;
}

Also tried combining the CSS above and a scroll function, but I don't think I'm targeting the active div right... How can I best target this active tab class in a scroll function? Or is there a better alternative to this method?

JsFiddle : https://jsfiddle.net/Lczsjz3y/7/

Any help would be appreciated :)

回答1:

From your fiddle, it looks like you just need to add a listener to the scroll event, because as you have it now, it just pulls the scrollTop() value on load. So, something similar to this:

$(window).on('scroll', function() {
   var scroll = $(window).scrollTop();
   if (scroll > 1000) {
     // change class
     $(this).find("navbar .active").css({
       "backgroundColor":"#000"
      });
   } else {
     // change it back
     $(this).find("navbar.active").css({
        "backgroundColor":"gray"
     });
   }
 });

Hope this helps.



回答2:

This will work:

$(window).scroll(function() {  
    var scroll = $(window).scrollTop();
    if (scroll >= 1000) {
        $(".navbar").css({"background-Color": "black"});
    } else {
        $(".navbar").css({"background-Color": "yellow"});
    }
});

Fiddle: https://jsfiddle.net/Lczsjz3y/21/



回答3:

It's not perfect and not the best solution, but I've tried playing around with what I know and manage to get what I wanted. https://jsfiddle.net/y791ur1x/3/

$(document).scroll(function () {

 var y = $(this).scrollTop();

 if (y >= 1100) {
  $('.navbar').removeClass("navbar-inverse").addClass("navbar-default");
  $(".navbar-custom").css({
    "backgroundColor":"#000000"
  });
 } else {
  $('.navbar').removeClass("navbar-default").addClass("navbar-inverse");
  $(".navbar-custom").css({
    "backgroundColor":"#222222"
  });
 }
});

Still look forward to a proper clean solution though!! ^^