먼저 큐에 대한 기본 지식이 필요합니다. 이전 장을 참조하세요.
관련 튜토리얼: jQuery에서의 애니메이션 처리 요약: http://www.jb51.net/article/42000.htm
jQuery 1.9.1 소스 코드 분석 시리즈(15) 애니메이션 처리 및 완화 애니메이션 코어 Tween: http://www.jb51.net/article/75821.htm
a. 애니메이션 입력 jQuery.fn.animate 함수 실행 과정에 대한 자세한 설명
---------------------------------- --- ---------------------
먼저 애니메이션 관련 매개변수를 얻기 위해 매개변수에 따라 jQuery.speed를 호출하고, 다음과 유사한 객체를 얻어 애니메이션 실행 함수 doAnimation을 생성합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | optall = {
complete: fnction(){...},
duration: 400,
easing: "swing" ,
queue: "fx" ,
old: false/fnction(){...},
}
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function () {
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
doAnimation.finish = function () {
anim.stop( true );
};
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
|
로그인 후 복사
실행 중인 애니메이션이 없으면 애니메이션이 즉시 실행되고, 그렇지 않으면 애니메이션이 애니메이션 대기열에 푸시되어 실행을 기다립니다.
1 2 3 4 | return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
|
로그인 후 복사
실제로 애니메이션이 실행되는 곳은 Animation( this, jQuery.extend( {}, prop ), optall ) 함수임을 알 수 있습니다
b. jQuery 내부 함수 Animation에 대한 자세한 설명
---------------------------------- --- ---------------------
애니메이션(요소, 속성, 옵션) 속성은 애니메이션화할 CSS 기능이고, 옵션은 애니메이션 관련 옵션입니다. "fx"}.
먼저 애니메이션 대기열을 처리하는 데 사용되는 지연 개체를 초기화합니다.
1 2 3 4 | deferred = jQuery.Deferred().always( function () {
delete tick.elem;
}),
|
로그인 후 복사
그런 다음 매 시점마다 실행될 함수 틱을 생성합니다(인접한 두 시점 사이의 이벤트 간격은 기본적으로 13밀리초입니다). 이 틱 함수는 jQuery.timers에 저장되며, 이후 매 시점마다 time jQuery.fx.tick이 실행될 때 꺼내서 실행됩니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | tick = function () {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
}
|
로그인 후 복사
jQuery의 애니메이션 진행 처리를 확인합니다.
1 | remaining = Math.max( 0, animation.startTime + animation.duration - currentTime )temp = remaining / animation.duration || 0,percent = 1 - temp,
|
로그인 후 복사
진행률 = 1 - 남은 시간 비율.
일반적으로 다음과 같이 처리합니다. 애니메이션이 13밀리초마다 한 번씩 실행되고, 현재 실행이 n번째이고, 총 애니메이션 지속 시간이 T라고 가정합니다. 그럼
진행률 = (n*13)/T
실제로 이 알고리즘으로 얻은 시간 n*13은 정확하지 않습니다. 왜냐하면 CPU가 단순히 프로그램을 실행하는 것이 아니고 사용자에게 할당된 시간 조각이 n*13보다 큰 경우가 많기 때문입니다. 더욱이 이는 매우 부정확한 값으로 인해 애니메이션이 빠르고 느리고 일관성이 없는 느낌을 줍니다. jQuery 방식은 현재 이벤트 시점에서의 애니메이션 실행 결과의 정확성을 보장한다.
셋째, 애니메이션에 사용되는 모든 기능으로 구성된 객체 애니메이션을 생성합니다(이 객체의 구조는 소스 코드와 같습니다). animation.props에 저장되는 것은 사용자가 전달한 기능입니다. (애니메이션의 최종 목표).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function ( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end ,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function ( gotoEnd ) {
var index = 0,
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
})
|
로그인 후 복사
넷째, CSS 기능 이름을 브라우저에서 인식할 수 있도록 propFilter를 호출합니다. borderWidth/padding/margin은 하나의 CSS 기능을 참조하는 것이 아니라 4개(상단, 하단)를 참조합니다. , 왼쪽, 오른쪽)
1 2 | propFilter( props, animation.opts.specialEasing );
|
로그인 후 복사
propFilter 보정 결과의 예를 들어보세요.
예시 1, CSS 기능 {height: 200}의 수정된 결과는 다음과 같습니다.
1 2 | props = { height: 200 }
animation.opts.specialEasing = {height: undefined}
|
로그인 후 복사
예시 2: CSS 기능 {margin:200}의 수정 결과는 다음과 같습니다.
1 2 | props = { marginBottom: 200,marginLeft: 200,marginRight: 200,marginTop: 200 }
animation.opts.specialEasing = { marginBottom: undefined,marginLeft: undefined,marginRight: undefined,marginTop: undefined }
|
로그인 후 복사
다섯째, 적응 처리를 위해 defaultPrefilter를 호출합니다. 예를 들어 높이/너비 애니메이션이 효과를 가지려면 표시 및 오버플로가 특정 값이어야 합니다. 예를 들어 표시/숨기기 애니메이션에는 많은 CSS가 필요합니다. 기능 값을 지정하고 함수에서 createTweens를 호출하여 이징 애니메이션을 생성합니다.
1 2 3 4 5 6 7 | for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
|
로그인 후 복사
animationPrefilters[index]의 값 함수는 defaultPrefilter입니다. defaultPrefilter 함수 처리에는 몇 가지 중요한 측면이 있습니다
DefaultPrefilter 포인트 1: 인라인 요소의 높이/너비 관련 애니메이션은 표시 기능 값을 inline-block으로 설정해야 합니다
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block" ;
} else {
style.zoom = 1;
}
}
}
|
로그인 후 복사
defaultPrefilter의 핵심 포인트 2: 높이/너비 애니메이션 오버플로의 경우 "숨김"으로 설정하고 애니메이션이 완료된 후 복원합니다. 이는 렌더링 속도를 향상시키는 데 도움이 됩니다.
1 2 3 4 5 6 7 8 9 10 11 12 | if ( opts.overflow ) {
style.overflow = "hidden" ;
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.always( function () {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
|
로그인 후 복사
DefaultPrefilter 포커스 3: 애니메이션 표시/숨기기의 특수 처리: 애니메이션 표시/숨기기는 genFx를 호출하여 모양을 얻습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 | props = {
height: "hide"
marginBottom: "hide"
marginLeft: "hide"
marginRight: "hide"
marginTop: "hide"
opacity: "hide"
paddingBottom: "hide"
paddingLeft: "hide"
paddingRight: "hide"
paddingTop: "hide"
width: "hide"
}
|
로그인 후 복사
애니메이션이 필요한 기능을 핸들 목록에 푸시하고 해당 기능을 삭제한 다음 해당 이징 애니메이션을 생성합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | for ( index in props ) {
value = props[ index ];
if ( rfxtypes. exec ( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle" ;
if ( value === ( hidden ? "hide" : "show" ) ) {
continue ;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow" , {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done( function () {
jQuery( elem ).hide();
});
}
anim.done( function () {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween. end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
|
로그인 후 복사
여섯 번째, 이징 애니메이션 생성, 표시/숨기기는 defaultPrefilter 함수(위 소스 코드)에서 처리되었습니다.
1 | createTweens( animation, props );
|
로그인 후 복사
我们来看一看createTweens中具体做了什么,先看一下createTweens之前的animation对象

然后看一下经过createTweens之后的animation对象的tweens数组变成了

将margin分解成了四个属性(marginTop/Right/Bottom/Left)并且每个属性都有自己的动画特征。
第七,启动动画计时,定时执行tick
1 2 3 4 5 6 7 8 | jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
|
로그인 후 복사
最后,将传入的动画结束回调加入延时队列
1 2 3 4 5 | return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
|
로그인 후 복사
Animation函数流程到此为止
拓展:
前面提到的genFx函数是专门用在toggle、hide、show时获取相关的需要动画的特征的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 最终生成的attrs = {
height: "show" ,
marginTop: "show" ,
marginRight: "show" ,
marginBottom: "show" ,
marginLeft: "show" ,
opacity: "show" ,
width: "show"
}
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
includeWidth = includeWidth? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
|
로그인 후 복사
Animation函数比较复杂,童鞋们可以随便使用例子去跟踪代码。这个是理解jQuery源码的一种比较好的方式。推荐两个例子:
第一个,有hide/show的例子:$("#id").hide(1000);
第二个,其他例子:$("#id").animate({"marginLeft":500},1000);
jQuery 1.9.1源码分析系列(十五)之动画处理 的全部内容就给大家介绍到这里,有问题随时给我留言,谢谢。!