如何不使用overflow CSS,实现窗口滚动时进度条随指定div联动?
Solution for Window-Scroll Linked Progress Bar
Hey there! Let's adjust your code to make the progress bar sync with window scroll instead of the #slide div's internal scroll. Here's how to do it step by step:
Key Changes Needed
- Remove the
overflowproperty from#slide(so it doesn't scroll internally anymore) - Switch the scroll event listener from
#slideto the globalwindowobject - Recalculate the progress based on
#slide's position relative to the window scroll
Modified Code
// Cache your elements for better performance const $slide = $('#slide'); const $progressBar = $('.your-progress-bar-selector'); // Replace with your actual progress bar selector // First, remove the overflow property from #slide (you can also do this in CSS directly) $slide.css('overflow', 'visible'); // Listen for window scroll events instead of #slide's scroll $(window).on('scroll', function() { // Get critical position values const slideTop = $slide.offset().top; const slideTotalScrollable = $slide[0].scrollHeight - $slide[0].clientHeight; const windowScrollPos = $(this).scrollTop(); // Calculate how much #slide has been scrolled past the viewport top // Clamp the value between 0 and the total scrollable height to avoid invalid values const scrolledAmount = Math.max(0, Math.min(windowScrollPos - slideTop, slideTotalScrollable)); // Calculate progress percentage (avoid division by zero if #slide isn't scrollable) const progressPercent = slideTotalScrollable > 0 ? (scrolledAmount / slideTotalScrollable) * 100 : 0; // Update the progress bar width $progressBar.width(`${progressPercent}%`); }); // Keep your original hover show/hide logic $slide.hover( () => $progressBar.show(), () => $progressBar.hide() );
How It Works
- Element Caching: We store references to
#slideand the progress bar to avoid repeated DOM queries, which boosts performance. - Overflow Removal: We clear the
overflowproperty on#slideso it no longer scrolls internally. - Window Scroll Listener: Instead of tracking scroll inside
#slide, we track the entire window's scroll position. - Progress Calculation:
slideTop: The distance from the top of the document to the top of#slide.slideTotalScrollable: The total amount#slidecan be scrolled (its full content height minus its visible height).scrolledAmount: How far#slidehas moved past the top of the viewport (we clamp this to valid ranges to prevent negative values or overflows).
- Progress Bar Update: We convert the scrolled amount to a percentage and apply it to the progress bar's width.
Edge Cases Handled
- If
#slideisn't tall enough to scroll (total scrollable height is 0), the progress bar stays at 0% to avoid division by zero errors. - When
#slidehasn't entered the viewport yet, the progress bar stays at 0%. - When
#slidehas fully scrolled past the viewport, the progress bar stays at 100%.
内容的提问来源于stack exchange,提问作者HELP
相关产品推荐
相关产品推荐

