滚动至顶部时进度条动画失效问题排查求助
Fix for Progress Bar Animation Failure When Scrolling Back to Top
Hey there! Let's break down why your progress bar isn't animating when you scroll back to the top, and how to fix it.
The Core Issues
Looking at your code, two main problems are causing the animation failure:
- Animation Queue Buildup: Every time you scroll, the
scrollevent fires repeatedly, adding multiple animation tasks to jQuery's queue. When you scroll back to the top, the queue is already filled with "shrink to 0" animations, so the "expand back" animation gets stuck waiting in line. - Hardcoded Width Values: You're using fixed values like
550pxfor the return animation, but these might not match the originalmax_widthvalues you captured on page load. This can cause inconsistencies or unexpected behavior.
The Fixed Code
Here's the adjusted code that resolves both issues:
var loader = $('#dottedProgressBar'); var loader2 = $('#dottedProgressBar2'); var loader3 = $('#dottedProgressBar3'); var time = 1300; var max_width = loader.width(); var max_width2 = loader2.width(); var max_width3 = loader3.width(); // Initial page load animation loader.width(0); loader2.width(0); loader3.width(0); loader.animate({ width: max_width }, time); loader2.animate({ width: max_width2 }, time); loader3.animate({ width: max_width3 }, time); $(document).scroll(function(){ // Clear existing animation queues and jump to end of current animations loader.stop(true, true); loader2.stop(true, true); loader3.stop(true, true); if ($(document).scrollTop() > 0) { loader.animate({ width: '0px', opacity: '0' }, 1300); loader2.animate({ width: '0px', opacity: '0' }, 1300); loader3.animate({ width: '0px', opacity: '0' }, 1300); } else { // Reuse the original max width values instead of hardcoding loader.animate({ width: max_width, opacity: '1' }, 300); loader2.animate({ width: max_width2, opacity: '1' }, 300); loader3.animate({ width: max_width3, opacity: '1' }, 300); } });
Key Changes Explained
stop(true, true): This is the critical fix. The firsttrueclears all pending animations from the queue, and the secondtrueforces the current animation to immediately finish at its target state. This ensures that when you scroll back to the top, the new "expand" animation starts right away instead of waiting.- Reusing
max_widthVariables: By using the original width values you captured on page load, you guarantee the progress bar returns to its exact initial state, avoiding mismatches from hardcoded numbers. - Simplified Condition: Replacing the separate
scrollTop() == 0check with anelsemakes the logic cleaner and covers all cases where the scroll position is at the top.
内容的提问来源于stack exchange,提问作者R.Lewandowski
相关产品推荐
相关产品推荐

