jQuery滚动菜单切换问题:需滚动500px后才触发显示隐藏效果
Let's tweak your existing jQuery code to add the 500px threshold requirement. The key is to only activate the toggle logic once the user has scrolled past that point, while still maintaining the original "hide on down-scroll, show on up-scroll" behavior once we're below 500px.
Here's the updated working code:
var prev = 0; var $window = $(window); var nav = $('.nav'); var scrollThreshold = 500; // Our 500px threshold $window.on('scroll', function(){ var scrollTop = $window.scrollTop(); // Only apply the toggle logic if we've scrolled past 500px if (scrollTop > scrollThreshold) { nav.toggleClass('hidden', scrollTop > prev); } else { // If we're above the threshold, make sure the menu is visible nav.removeClass('hidden'); } // Update previous scroll position prev = scrollTop; });
Key Changes Explained:
- Added a
scrollThresholdvariable to define our 500px limit (easy to adjust later if needed) - Wrapped the toggle logic in an
ifstatement that checks if we've scrolled past the threshold - Added an
elseclause to ensure the menu stays visible when the user is above 500px (prevents accidental hiding when scrolling up from below the threshold) - Kept the core
toggleClasslogic intact, so once past 500px, the menu still hides on down-scroll and shows on up-scroll
CSS Note:
For a smooth user experience, make sure your .hidden class uses a transition instead of abrupt hiding:
.nav { transition: transform 0.3s ease; position: fixed; top: 0; width: 100%; } .nav.hidden { transform: translateY(-100%); }
内容的提问来源于stack exchange,提问作者Dan382
相关产品推荐
相关产品推荐

