您已经给出了解决方案,但看起来该行为可能是 jQuery animate 函数的行为方式。我想我会提供一个答案来解释这种行为。我不确定这是错误还是预期行为。对我来说,它看起来更像是一个错误。
当你调用 animate 函数时,它在内部调用了一个 adjustCSS 函数。调用 adjustCSS 的调用栈很长(animate() -> dequeue() -> doAnimation() -> Animation() -> jquery.map() -> createTween() -> Animation.Tweeners.*0 > adjustCSS ()) 以防万一您对流程感兴趣。
在adjustCSS内部,代码执行路径在进度条为0%时采用不同的路由集合,在进度条为50%时采用不同的路由集合。
如果你看到了adjustCSS
function adjustCSS( elem, prop, valueParts, tween ) {
var adjusted,
scale = 1,
maxIterations = 20,
currentValue = tween ?
function() {
return tween.cur();
} :
function() {
return jQuery.css( elem, prop, "" );
},
initial = currentValue(),
unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
rcssNum.exec( jQuery.css( elem, prop ) );
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || initialInUnit[ 3 ];
// Make sure we update the tween properties later on
valueParts = valueParts || [];
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1;
do {
// If previous iteration zeroed out, double until we get *something*.
// Use string for doubling so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
initialInUnit = initialInUnit / scale;
jQuery.style( elem, prop, initialInUnit + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// Break the loop if scale is unchanged or perfect, or if we've just had enough.
} while (
scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
);
}
if ( valueParts ) {
initialInUnit = +initialInUnit || +initial || 0;
// Apply relative offset (+=/-=) if specified
adjusted = valueParts[ 1 ] ?
initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
+valueParts[ 2 ];
if ( tween ) {
tween.unit = unit;
tween.start = initialInUnit;
tween.end = adjusted;
}
}
return adjusted;
}
点击第一个按钮时,initialInUnit为0,不经过if条件
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
直接跳转到
if ( valueParts ) {
但是当您第二次单击该按钮时,它会通过上面的第一个 if 条件,因为进度条已经处于其 50% 的宽度。现在是什么使百分比 315% 或出现的任何数字是奇怪的行为所在。
当它经过if条件时,有一条语句:
jQuery.style( elem, prop, initialInUnit + unit );
这里 jQuery 将元素的 width 属性设置为 initialInUnit 中的值,它是进度条的宽度,以像素为单位,并以 % 为单位附加单位。因此,它不是将宽度从 50% 设置为 100%,而是将宽度从 315% 设置为 100%。这 315% 可以根据进度条的宽度而变化。
事实上,你甚至不需要第二个按钮来复制行为,如果你点击按钮 1 秒,你可以看到它的动画从 315%(或其他)到 50%。
所以我不确定这是否是一个错误(虽然它看起来像一个)。调整后的 CSS 可能适用于其他条件。向 jQuery 团队提出问题以检查 adjustCSS 函数中 initialInUnit 值分配的预期行为可能是值得的。
adjustCSS 函数是 jQuery 代码的一部分,如 here 所示