简体   繁体   中英

Change navbar background color on page scroll

Im having trouble getting my fixed top navbar to change background-color when I scroll the page.

Here is the function in JS:

$(document).ready(function(){       
    var scroll_start = 0;
    var startchange = $('#startchange');
    var offset = startchange.offset();
    if (startchange.length){
        $(document).scroll(function() { 
            scroll_start = $(this).scrollTop();
            if(scroll_start > offset.top) {
                $(".navbar").css('background-color', '#f0f0f0');
            } else {
                $('.navbar').css('background-color', 'transparent');
            }
        });
    }
 });

This is a file called " custom.js " and loaded at the bottom of the page AFTER I load bootstrap and jquery ( custom.js is in the same folder as index.html )

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="custom.js"></script>

Here is the html navbar:

<div class="container">
    <nav class="navbar navbar-default navbar-fixed-top">
        <div class="container-fluid">
            <div class="navbar-header ">                  
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbarNav">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
            </div>

            <div id="navbarNav" class="navbar-collapse collapse ">
                <br/><br/>
                <ul class="nav navbar-nav navbar-right ">
                    <li><a href="#">ABOUT</a></li>
                    <li><a href="#">SERVICES</a></li>
                    <li><a href="#">CONTACT</a></li>
                    <li><a href="#">CALCULATORS</a></li>
                </ul>
            </div> 
        </div>
    </nav>
</div>

And then only css I have for navbar background color change:

.navbar {
    background-color: transparent;
    border-color: transparent;
}

.navbar-toggle:hover, .navbar-default .navbar-toggle:focus{
    background-color: transparent !important;
}

This is what your current function and css does on a page that has a <div> with id=startchange . On page load the navbar is not transparent. As soon as you scroll the navbar becomes transparent (border still visible) and once the <div> with id=startchange passes the top of the page you navbar becomes non transparent again.

If you make your css more specific you can get the navbar to be transparent to start with no border (at larger screen sizes, you might want to look at how its styled for smaller screens too).

 $(document).ready(function(){ var scroll_start = 0; var startchange = $('#startchange'); var offset = startchange.offset(); if (startchange.length){ $(document).scroll(function() { scroll_start = $(document).scrollTop(); if(scroll_start > offset.top) { $(".navbar").css('background-color', '#f0f0f0'); } else { $('.navbar').css('background-color', 'transparent'); } }); } });
 .navbar.navbar-default.navbar-fixed-top { background-color: transparent; border-color: transparent; -webkit-transition: background-color 2s; /* Safari */ transition: background-color 2s; } .navbar-toggle:hover, .navbar-default .navbar-toggle:focus{ background-color: transparent !important; }
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <div class="container"> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header "> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbarNav"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div id="navbarNav" class="navbar-collapse collapse "> <br/><br/> <ul class="nav navbar-nav navbar-right "> <li><a href="#">ABOUT</a></li> <li><a href="#">SERVICES</a></li> <li><a href="#">CONTACT</a></li> <li><a href="#">CALCULATORS</a></li> </ul> </div> </div> </nav> <div id="page"> Page Top <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <div id="startchange">Start Change Div</div> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> Page Bottom </div> </div>

Change value 50 as needed, 50px is page position after scroll

$(document).ready(function () {
                    $(window).scroll(function () {
                        if ($(window).scrollTop() >= 50) {
                            $(".navbar").css("background-color", "#222");
                        } else {
                            $(".navbar").css("background-color", "transparent");
                        }
                    });
                });

This way is very easy;

let blackToRed = [0,0,0,1];
$(document).ready(function(){
    $(document).scroll(function() {
        blackToRed[0] = window.scrollY;
        $("#item").css('color', 'rgba(' + blackToRed + ')');
    });
});

this is the simplest way to do it using pure JavaScript HTML DOM set the nav tag id to id="navbar" and also depending on where are you going to place your js code if you are going to apply it on the same page place the below code inside the script tags other wise just paste the code as is in your js file the navbar background color is transparent and onscroll the navbar change to red

 // When the user scrolls down 80px from the top of the document, resize the navbar's padding and the logo's font size window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) { document.getElementById("navbar").style.backgroundColor = "red"; // document.getElementById("logo").style.fontSize = "25px"; } else { document.getElementById("navbar").style.backgroundColor = "transparent"; // document.getElementById("logo").style.fontSize = "35px"; } }
 * {box-sizing: border-box;} body { margin: 0; font-family: Arial, Helvetica, sans-serif; } #navbar { overflow: hidden; background-color: #f1f1f1; padding: 90px 10px; transition: 0.4s; position: fixed; width: 100%; top: 0; z-index: 99; } #navbar a { float: left; color: black; text-align: center; padding: 12px; text-decoration: none; font-size: 18px; line-height: 25px; border-radius: 4px; } #navbar #logo { font-size: 35px; font-weight: bold; transition: 0.4s; } #navbar a:hover { background-color: #ddd; color: black; } #navbar a.active { background-color: dodgerblue; color: white; } #navbar-right { float: right; } @media screen and (max-width: 580px) { #navbar { padding: 20px 10px !important; } #navbar a { float: none; display: block; text-align: left; } #navbar-right { float: none; }
 <div id="navbar"> <a href="#default" id="logo">CompanyLogo</a> <div id="navbar-right"> <a class="active" href="#home">Home</a> <a href="#contact">Contact</a> <a href="#about">About</a> </div> </div> <div style="margin-top:210px;padding:15px 15px 2500px;font-size:30px"> <p><b>changing nav bar on scroll.</b></p> <p>Scroll down to see the effect!</p> <p>Scroll to the top to remove the effect.</p> What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). </p> </div>

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