如何重置jQuery粘性导航栏的滚动样式切换功能?
Hey there! I see the issue with your sticky navbar—it's only switching back to white when you scroll all the way to the top, not when you leave the .stickychange section. Let's break down why this happens and fix it.
The Root Problem
Your current code only checks if the scroll position is above the top of the .stickychange section (scroll_start > offset.top). But once you scroll past the entire .stickychange area (into the white section below), scroll_start is still greater than offset.top—so the else block never triggers. You need to check if the scroll position is within the bounds of the .stickychange section instead of just its top edge.
The Fix
We'll calculate the bottom edge of the .stickychange section, then only apply the dark navbar style when the scroll position is between the section's top and bottom. Here's the updated code:
var scroll_start = 0; // Fix: Add the dot for class selector var startchange = $(".stickychange"); if (startchange.length) { // Check if the element exists (more reliable than just "if (startchange)") var offset = startchange.offset(); // Calculate the bottom of the .stickychange section var sectionBottom = offset.top + startchange.outerHeight(); $(document).scroll(function () { scroll_start = $(this).scrollTop(); // Only apply dark style if scroll is within the .stickychange section if (scroll_start > offset.top && scroll_start < sectionBottom) { $("#menu_top").css({ 'background-color': 'rgba(0,0,0,0.5)', 'transition': 'all 0.2s ease-in' }); $("#menu_top a").addClass("stickyspecial"); $("#menu_top h2").addClass("stickyname"); } else { // Reset to default style when outside the section (above OR below) $('#menu_top').css('background-color', '#fff'); $('#menu_top a').removeClass("stickyspecial"); $('#menu_top h2').removeClass("stickyname"); } }); }
Key Changes Explained
- Fixed selector: Changed
$("stickychange")to$(".stickychange")(you forgot the dot for class selection—this was probably preventing the element from being detected properly!) - Added section bottom calculation:
sectionBottom = offset.top + startchange.outerHeight()gives us the pixel position of the bottom of your target section. - Updated condition: Now we check if
scroll_startis between the section's top and bottom. If yes, apply the dark style; if not (whether you're above the section or below it), reset to the white navbar.
Bonus Tip
Using .css({ ... }) with an object is cleaner than calling .css() multiple times for the same element—it just makes your code a bit more concise!
内容的提问来源于stack exchange,提问作者Steven LUU

