简体   繁体   中英

Navbar to change colour on scroll bootstrap 4

Hi guys so i want my navbar to be able to switch colors from transparent to black as soon as the user scrolls, now this code worked on my bootstrap 3 website but when i have changed to bootstrap 4 it didn't work for some reason

html:

<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="mainNav" role="navigation">
...
  </nav>

CSS: This just making it transparent

.bg-dark {
      background-color: rgba(255, 0, 0, 0)!important;
      padding-top: 20px;
}

javascript :

       $(document).ready(function(){

     var checkScrollBar = function(){
       $('.bg-dark').css({
         backgroundColor: $(this).scrollTop() > 1 ?
           'rgb(0, 0, 0)' : 'transparent'
       })
     }
     $(window).on('load resize scroll', checkScrollBar)
     });

Again this was working on my other site but on this one i cant seem to get it to work for some reason ,

thanks

I got this to work by removing !important rule in your CSS. With that rule there, jQuery will change the background colour inline, but the browser will choose the !important style over the change, so it will not be visually reflected.

This whole line might be unnecessary because you are using jQuery to set the background color to transparent anyway:

background-color: rgba(255, 0, 0, 0)!important;

With Javascript only :

<!-- Custom JS for background color on scrolling -->
<script>
    $(window).scroll(function(){
    var scroll = $(window).scrollTop();
    if(scroll < 300){
        $('.fixed-top').css('background', 'transparent');
    } else{
        $('.fixed-top').css('background', 'rgba(0, 0, 0, 0.4)');
    }
});
</script>

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