如何在jQuery的fadeOut动画中正确实现progress选项?
jQuery fadeOut 动画进度回调的正确实现方式
你遇到的问题核心是:jQuery 的 fadeOut() 方法本身不支持直接传入进度回调函数。它的参数结构为 fadeOut(duration, easing, complete),你把 progress 函数作为第二个参数传入时,它会被当作缓动函数而非进度回调,因此函数内的参数无法获取正确值,输出 undefined。
要实现 fadeOut 动画的进度监听,正确的做法是用 animate() 方法手动模拟 fadeOut 的行为——因为 animate() 支持配置 progress 回调,而 fadeOut 本质就是对元素 opacity 属性从 1 到 0 的动画,最终隐藏元素。
正确代码示例
$(window).on("load", function() { var timer = 1000; $(".loader-wrapper").animate( { opacity: 0 }, // 模拟fadeOut的透明度变化 { duration: timer, // 进度回调函数 progress: function(animation, progress, remainingMs) { // progress 是 0~1 的小数,代表动画完成比例 var progressPercent = Math.round(progress * 100); console.log("动画完成进度:" + progressPercent + "%"); console.log("剩余时间:" + remainingMs + "ms"); }, // 动画结束后隐藏元素,对齐fadeOut的最终效果 complete: function() { $(this).css("display", "none"); } } ); });
补充说明
animate()的配置对象中,progress回调的三个参数分别为:动画实例对象、完成进度(0~1)、剩余时长(毫秒),可以根据需求使用这些参数。- 如果尝试用全局钩子
$.fx.step监听进度,虽然能实现,但会影响页面上所有同属性的动画,不推荐在精准需求场景下使用:
// 不推荐:会影响所有opacity动画 $.fx.step.opacity = function(fx) { if (fx.elem.classList.contains("loader-wrapper")) { console.log("进度:", fx.pos); // fx.pos 是0~1的进度值 } }; $(".loader-wrapper").fadeOut(1000);
内容的提问来源于stack exchange,提问作者Extan
相关产品推荐
相关产品推荐

