change color navbar after scroll

前端 未结 2 1510
灰色年华
灰色年华 2020-12-22 01:11

i want to change the color of my navbar when i scroll. When the navbar is on top the background is transparent. thank\'s to all for the attention and excuse me for my bad en

相关标签:
2条回答
  • 2020-12-22 01:54

    Use the Bootstrap Affix component to watch the scroll position instead of extra jQuery/JavaScript. Just define the .affix-top and .affix CSS for the navbar.

       /* navbar style once affixed to the page */ 
       .affix {
             background-color: black;   
        }
    
        @media (min-width:768px) {
            .affix-top {
              /* navbar style at top */
              background-color:transparent;
              border-color:transparent;
              padding: 15px; 
            }
        }
    

    and set the position you want the navbar to change style (ie; 400px from the top)

    <div class="navbar navbar-inverse navbar-fixed-top" data-spy="affix" data-offset-top="400">
    

    Working Demo: http://www.codeply.com/go/xp2fY6sVHP


    For Bootstrap 4, see: Animate/Shrink NavBar on scroll using Bootstrap 4

    0 讨论(0)
  • 2020-12-22 02:10

    jQuery

    /**
     * Listen to scroll to change header opacity class
     */
    function checkScroll(){
        var startY = $('.navbar').height() * 2; //The point where the navbar changes in px
    
        if($(window).scrollTop() > startY){
            $('.navbar').addClass("scrolled");
        }else{
            $('.navbar').removeClass("scrolled");
        }
    }
    
    if($('.navbar').length > 0){
        $(window).on("scroll load resize", function(){
            checkScroll();
        });
    }
    
    0 讨论(0)
提交回复
热议问题