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

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

  还有一个比较关键的地方是都用了this.createTween获取单个css特征的基础的动画特征。而animation. createTween中直接调用jQuery.Tween来处理。接下来我们详解之。

a.jQuery.Tween

——————————————————————————–

  jQuery.Tween的结构和jQuery类似


function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {...},
run: function( percent ) {...}
};
Tween.prototype.init.prototype = Tween.prototype;

  是不是有一种很熟悉的赶脚。

  里面cur函数用来获取当前的css特征值


cur: function() {
var hooks = Tween.propHooks[ this.prop ];

return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},

  而run函数则会在每个动画时间点上对正在进行的动画的每个特征值进行处理。

  主要是两个步骤:

  1.计算动画当前进度pos和动画当前位置now


//如果有动画时长则使用jQuery.easing计算出缓动动画进度eased,否则进度eased为percent
//并根据进度得到当前动画位置now
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;

  2.根据当前进度情况设置css特征值


//设置css特征值
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;

  可见生成缓动动画这一步处理才是整个动画的核心:

  创建缓动动画组,每一个原子动画都包含了每一个原子css属性动画的各种必要参数以及动画函数

  不同的是hide/show直接在defaultPrefilter中创建了这个缓动动画组(所有的属性都默认是px单位),其他的动画在调用createTweens时创建缓动动画组。