基于jquery.viewport实现固定区域随特定视口元素显隐
Solution for Toggling Sticky Element Based on Section Visibility
Got it, let's get this working smoothly for you. The goal is to show/hide the fixed .sticky-info element depending on whether #section-2 is in the viewport. We'll use the jquery.viewport plugin for the visibility check, plus add some performance tweaks to avoid jank from frequent scroll events.
Step 1: Clean Up Your HTML
First, let's make the HTML structure clearer (this is optional but helps with readability):
<section id="section-1"> <div class="sticky-info">Sticky</div> </section> <section id="section-2"> <!-- Add your content for section 2 here --> </section>
Step 2: Add CSS for Fixed Positioning
Don't forget to style the sticky element so it stays fixed on the page:
.sticky-info { position: fixed; top: 20px; right: 20px; padding: 10px 15px; background-color: #ffffff; border: 1px solid #e0e0e0; z-index: 1000; /* Ensure it stays above other content */ } /* Optional: Set section heights to test scrolling behavior */ #section-1, #section-2 { height: 100vh; /* Makes each section take full viewport height */ }
Step 3: Complete the JavaScript
We'll add a debounce function to limit how often our scroll logic runs (since scroll events fire constantly), plus handle the initial state when the page loads:
// Debounce function to optimize scroll event performance function debounce(func, delay) { let timeoutId; return function() { const context = this; const args = arguments; clearTimeout(timeoutId); timeoutId = setTimeout(() => func.apply(context, args), delay); }; } // Handle scroll event with debounce $(window).scroll(debounce(function() { const $section2 = $('#section-2'); const $stickyInfo = $('.sticky-info'); if ($section2.is(':in-viewport')) { // Hide sticky element only if it's currently visible if ($stickyInfo.is(':visible')) { $stickyInfo.fadeOut(100); } } else { // Show sticky element only if it's currently hidden if (!$stickyInfo.is(':visible')) { $stickyInfo.fadeIn(100); } } }, 50)); // Adjust delay as needed (50ms is a good starting point) // Set initial state when the page loads $(document).ready(function() { const $section2 = $('#section-2'); const $stickyInfo = $('.sticky-info'); if ($section2.is(':in-viewport')) { $stickyInfo.hide(); } else { $stickyInfo.show(); } });
Key Details to Note:
- Debouncing: This prevents our visibility check from running hundreds of times per second while scrolling, which can cause performance issues. The 50ms delay means the logic runs only after scrolling stops for 50ms.
- Avoid Duplicate Animations: We check if
.sticky-infois already visible/hidden before triggeringfadeIn/fadeOut—this prevents unnecessary animation queues. - Initial State Handling: The
document.readyblock ensures the sticky element starts in the correct state even before the user scrolls.
内容的提问来源于stack exchange,提问作者Max Di Campo
相关产品推荐
相关产品推荐

