导航Div提前50px固定(仅适配窗口宽度>800px)需求
Got it, let's merge your two scripts into one that hits all your requirements: only trigger the fixed position when the window is wider than 800px, fix the .navPages-container 50px before it would scroll out of view, and add a bottom border when it's fixed.
Here's the complete working code:
<script type="text/javascript"> // Cache the navigation container element for better performance const navContainer = $('.navPages-container'); // Get the initial top position of the nav on page load const originalNavTop = navContainer.offset().top; // Calculate the scroll trigger point: 50px before the nav reaches the viewport top const triggerScrollOffset = originalNavTop - 50; // Track if the nav is currently in fixed state to avoid redundant style updates let isNavFixed = false; // Listen to both scroll and resize events to handle window width changes $(window).on('scroll resize', function() { const currentScrollPos = $(window).scrollTop(); const currentWindowWidth = $(window).width(); // Only apply fixed navigation logic if window is wider than 800px if (currentWindowWidth > 800) { // Fix the nav when scroll passes the trigger offset (and it's not already fixed) if (currentScrollPos >= triggerScrollOffset && !isNavFixed) { navContainer.css({ position: 'fixed', top: '52px', height: '50px', left: '0', borderBottom: '1px solid #000' }); isNavFixed = true; } // Reset to static position when scrolling back above the trigger offset else if (currentScrollPos < triggerScrollOffset && isNavFixed) { navContainer.css({ position: 'static', top: '0', borderBottom: 'none' }); isNavFixed = false; } } // If window is resized to <=800px, immediately reset nav to static state else if (isNavFixed) { navContainer.css({ position: 'static', top: '0', borderBottom: 'none' }); isNavFixed = false; } }); </script>
Key details of this implementation:
- Early trigger logic: We calculate the scroll point by subtracting 50px from the nav's original top position, so it fixes before it would scroll out of view.
- Resize handling: Added a
resizeevent listener to instantly revert the nav to static if the window is resized below 800px. - Performance optimization: The
isNavFixedflag prevents unnecessary CSS updates on every scroll tick—we only modify styles when the fixed state actually changes. - Border control: Explicitly adds/removes the
border-bottomstyle when toggling the fixed state, ensuring it only appears when the nav is fixed.
内容的提问来源于stack exchange,提问作者ZEDG
相关产品推荐
相关产品推荐

