Home >Web Front-end >CSS Tutorial >How to Dynamically Change Navigation Bar Color on Scroll?
How to Change Navigation Bar Color When Scrolling
Problem:
Setting a transparent background color for the navigation bar doesn't work when the page is scrolled, resulting in a new background color being applied.
Solution:
To change the navigation bar color after scrolling, follow these steps:
Add JavaScript to the Head:
$(function () { $(document).scroll(function () { var $nav = $(".navbar-fixed-top"); $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height()); }); });
Add CSS to Style the Navigation Bar:
.navbar-fixed-top.scrolled { background-color: #fff !important; transition: background-color 200ms linear; }
Implementation:
The JavaScript code watches for page scrolling. Once the scroll exceeds the height of the navigation bar, it adds a class named scrolled to the navigation bar. The CSS code styles the navigation bar with a white background color when the scrolled class is present. This transitions the background color smoothly over 200 milliseconds.
This solution allows you to set a transparent background color for the navigation bar when it's not scrolled and change the background color to white when scrolling occurs.
The above is the detailed content of How to Dynamically Change Navigation Bar Color on Scroll?. For more information, please follow other related articles on the PHP Chinese website!