jQuery 1.9.1源码分析系列(十五)动画处理之缓动动画核心Tween

2020-05-27 18:13:11易采站长站整理

在jQuery内部函数Animation中调用到了createTweens()来创建缓动动画组,创建完成后的结果为:

  可以看到上面的缓动动画组有四个原子动画组成。每一个原子动画的信息都包含在里面了。

  仔细查看createTweens函数,实际上就是遍历调用了tweeners [“*”]的数组中的函数(实际上就只有一个元素)。


function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}

  再次查看这个tweeners [“*”][0]函数,主要代码如下


function( prop, value ) {
var end, unit,
//根据css特征值获取缓动动画结构
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
//非像素单位的属性
if ( unit !== "px" && start ) {
// 从一个非零起点开始迭代,
//对于当前属性,如果它使用相同的单位这一过程将是微不足道
// 后备为end,或一个简单的常量
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
//如果前一次迭代为零,加倍,直到我们得到*东西*
//使用字符串倍增因子,所以我们不会偶然看到scale不改变
scale = scale || ".5";
// 调整和运行
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// 更新scale, 默认0或NaN从tween.cur()获取
// 跳出循环,如果scale不变或完成时, 或者我们已经觉得已经足够了
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
//如果提供了+=/-=记号,表示我们正在做一个相对的动画
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]};

  可以看出除了hide/show两种动画外的其他动画都经过tweeners [“*”][0]这个函数封装了动画组。其中有几个关键的数组start/end/unit。特别是对非像素单位的动画start值获取费了一番功夫。