如何在滚动时用纯CSS切换导航栏中的图片?
Hey there! I see you’ve already nailed switching the link text color when your navbar enters the fixed state—nice work! Now you’re stuck on swapping the logo image too, and that old Stack Overflow answer you referenced isn’t cutting it. Let’s fix that.
First, quick context: That older answer talks about using CSS to set an equivalent of src for images, but the catch is CSS content only works with pseudo-elements (like ::before/::after), not directly on <img> tags. So we need a different approach.
Here are two solid solutions tailored to your HTML structure:
Solution 1: Use CSS Background Images (No JS Needed)
This method swaps out the logo by replacing the <img> with a background image, which we can toggle with CSS classes.
First, update your HTML to replace the <img> with a div that will hold the background:
<div class="logo-box"> <div class="logo"> <a href="#"> <div class="logo-img"></div> </a> </div> </div>
Then add this CSS. Replace the width/height values with your actual logo dimensions, and update the second image path to your fixed-state logo:
.logo-img { width: 120px; /* Adjust to your logo's width */ height: 40px; /* Adjust to your logo's height */ background-image: url('images/logo.png'); background-size: contain; background-repeat: no-repeat; background-position: center; } /* Assume your navbar gets a .fixed class when it sticks */ .navbar.fixed .logo-img { background-image: url('images/logo-fixed.png'); /* Your alternate logo */ }
Solution 2: Use JavaScript to Toggle the img src
If you prefer keeping the <img> tag as-is, use JavaScript to listen for scroll events and update the src attribute when the navbar becomes fixed.
Add this script to your page (make sure it runs after the DOM loads):
// Wait for the page to fully load document.addEventListener('DOMContentLoaded', function() { const navbar = document.querySelector('.navbar'); // Target your navbar element const logoImg = document.querySelector('.logo img'); // Listen for scroll events window.addEventListener('scroll', function() { // Check if navbar has the fixed class (adjust the class name to match yours) if (navbar.classList.contains('fixed')) { logoImg.src = 'images/logo-fixed.png'; } else { logoImg.src = 'images/logo.png'; } }); // Also run once on page load to set the correct initial state if (navbar.classList.contains('fixed')) { logoImg.src = 'images/logo-fixed.png'; } });
Either of these methods will get your logo swapping smoothly when the navbar sticks. Pick the one that fits your workflow best!
内容的提问来源于stack exchange,提问作者eeduardogarcia

