,十二jQuery内置特效的实现

jQuery内置特效的实现用了两段extend代码。

第一段jQuery.fn.extend扩展了jQuery.fn上的常见特效方法。其中重要的animate方法。

第二段jQuery.extend 定义了重要的fx方法、speed方法。支持animate的实现。

第一段jQuery.fn.extend

jQuery.fn.extend({
// overwrite the old show method
_show: jQuery.fn.show,
show: function(speed,callback){
return speed ? this.animate({
height: "show", width: "show", opacity: "show"
}, speed, callback) : this._show();
},
// Overwrite the old hide method
_hide: jQuery.fn.hide,
hide: function(speed,callback){
return speed ? this.animate({
height: "hide", width: "hide", opacity: "hide"
}, speed, callback) : this._hide();
},
slideDown: function(speed,callback){
return this.animate({height: "show"}, speed, callback);
},
slideUp: function(speed,callback){
return this.animate({height: "hide"}, speed, callback);
},
slideToggle: function(speed,callback){
return this.each(function(){
var state = $(this).is(":hidden") ? "show" : "hide";
$(this).animate({height: state}, speed, callback);
});
},
fadeIn: function(speed,callback){
return this.animate({opacity: "show"}, speed, callback);
},
fadeOut: function(speed,callback){
return this.animate({opacity: "hide"}, speed, callback);
},
fadeTo: function(speed,to,callback){
return this.animate({opacity: to}, speed, callback);
},
animate: function(prop,speed,callback) {
return this.queue(function(){
this.curAnim = prop;
for ( var p in prop ) {
var e = new jQuery.fx( this, jQuery.speed(speed,callback), p );
if ( prop[p].constructor == Number )
e.custom( e.cur(), prop[p] );
else
e[ prop[p] ]( prop );
}
});
},
queue: function(type,fn){
if ( !fn ) {
fn = type;
type = "fx";
}
return this.each(function(){
if ( !this.queue )
this.queue = {};
if ( !this.queue[type] )
this.queue[type] = [];
this.queue[type].push( fn );
if ( this.queue[type].length == 1 )
fn.apply(this);
});
}
});

animate之前的函数实现都是一句话调用了animate实现,使其支持特效。show和hide重写了原先定义的show和hide方法。animte调用了queue方法将构造的特效处理方法进行了排队。animate中调用的fx方法和 speed方法均定义在第二段jQuery.extend代码中:

jQuery.extend({
setAuto: function(e,p) {
...
},
speed: function(s,o) {
o = o || {};
if ( o.constructor == Function )
o = { complete: o };
var ss = { slow: 600, fast: 200 };
o.duration = (s && s.constructor == Number ? s : ss[s]) || 400;
// Queueing
o.oldComplete = o.complete;
o.complete = function(){
jQuery.dequeue(this, "fx");
if ( o.oldComplete && o.oldComplete.constructor == Function )
o.oldComplete.apply( this );
};
return o;
},
queue: {},
dequeue: function(elem,type){
type = type || "fx";
if ( elem.queue && elem.queue[type] ) {
// Remove self
elem.queue[type].shift();
// Get next function
var f = elem.queue[type][0];
if ( f ) f.apply( elem );
}
},
/*
* I originally wrote fx() as a clone of moo.fx and in the process
* of making it small in size the code became illegible to sane
* people. You've been warned.
*/
fx: function( elem, options, prop ){
...
}
});

setAuto这个函数在这里出现显得不明所以,之前看过的代码里没有对setAuto的引用。向后查找一下发现在fx中调用了setAuto。所以setAtuo的理解要结合fx理解。剩余的speed 和 dequeue很好理解。dequeue被speed中定义的complete方法调用。用于将完成的特效处理方法移除。queue不能和上面jQuery.fn.extend中的queue相关代码联系。这里的queue是定义与jQuery之上的。我们知道jQuery通过13秒的间隔来执行一个指定的函数。没错这个queue就是为这个13秒间隔执行的函数提供队列的。speed方法控制了特效执行的速度并添加了对特效完成时的清理工作。注意到dequeue和queue的实现,两个函数都支持传递type,但是在所有的调用里。queue由于只传入了一个参数所以type='fx',而dequeue则指明为'fx'。上面代码中定义的queue属性是不是略显多余,因为queue和dequeue操作的都是jQuery对象关联的DOM元素上的queue属性中的内容?

看一下setAuto和fx的代码:

setAuto: function(e,p) {
if ( e.notAuto ) return;
if ( p == "height" && e.scrollHeight != parseInt(jQuery.curCSS(e,p)) ) return;
if ( p == "width" && e.scrollWidth != parseInt(jQuery.curCSS(e,p)) ) return;
// Remember the original height
var a = e.style[p];
// Figure out the size of the height right now
var o = jQuery.curCSS(e,p,1);
if ( p == "height" && e.scrollHeight != o ||
p == "width" && e.scrollWidth != o ) return;
// Set the height to auto
e.style[p] = e.currentStyle ? "" : "auto";
// See what the size of "auto" is
var n = jQuery.curCSS(e,p,1);
// Revert back to the original size
if ( o != n && n != "auto" ) {
e.style[p] = a;
e.notAuto = true;
}
}
fx: function( elem, options, prop ){
var z = this;
// The users options
z.o = {
duration: options.duration || 400,
complete: options.complete,
step: options.step
};
// The element
z.el = elem;
// The styles
var y = z.el.style;
// Simple function for setting a style value
z.a = function(){
if ( options.step )
options.step.apply( elem, [ z.now ] );
if ( prop == "opacity" ) {
if (z.now == 1) z.now = 0.9999;
if (window.ActiveXObject)
y.filter = "alpha(opacity=" + z.now*100 + ")";
else
y.opacity = z.now;
// My hate for IE will never die
} else if ( parseInt(z.now) )
y[prop] = parseInt(z.now) + "px";
y.display = "block";
};
// Figure out the maximum number to run to
z.max = function(){
return parseFloat( jQuery.css(z.el,prop) );
};
// Get the current size
z.cur = function(){
var r = parseFloat( jQuery.curCSS(z.el, prop) );
return r && r > -10000 ? r : z.max();
};
// Start an animation from one number to another
z.custom = function(from,to){
z.startTime = (new Date()).getTime();
z.now = from;
z.a();
z.timer = setInterval(function(){
z.step(from, to);
}, 13);
};
// Simple 'show' function
z.show = function( p ){
if ( !z.el.orig ) z.el.orig = {};
// Remember where we started, so that we can go back to it later
z.el.orig[prop] = this.cur();
z.custom( 0, z.el.orig[prop] );
// Stupid IE, look what you made me do
if ( prop != "opacity" )
y[prop] = "1px";
};
// Simple 'hide' function
z.hide = function(){
if ( !z.el.orig ) z.el.orig = {};
// Remember where we started, so that we can go back to it later
z.el.orig[prop] = this.cur();
z.o.hide = true;
// Begin the animation
z.custom(z.el.orig[prop], 0);
};
// IE has trouble with opacity if it does not have layout
if ( jQuery.browser.msie && !z.el.currentStyle.hasLayout )
y.zoom = "1";
// Remember the overflow of the element
if ( !z.el.oldOverlay )
z.el.oldOverflow = jQuery.css( z.el, "overflow" );
// Make sure that nothing sneaks out
y.overflow = "hidden";
// Each step of an animation
z.step = function(firstNum, lastNum){
var t = (new Date()).getTime();
if (t > z.o.duration + z.startTime) {
// Stop the timer
clearInterval(z.timer);
z.timer = null;
z.now = lastNum;
z.a();
z.el.curAnim[ prop ] = true;
var done = true;
for ( var i in z.el.curAnim )
if ( z.el.curAnim[i] !== true )
done = false;
if ( done ) {
// Reset the overflow
y.overflow = z.el.oldOverflow;
// Hide the element if the "hide" operation was done
if ( z.o.hide )
y.display = 'none';
// Reset the property, if the item has been hidden
if ( z.o.hide ) {
for ( var p in z.el.curAnim ) {
y[ p ] = z.el.orig[p] + ( p == "opacity" ? "" : "px" );
// set its height and/or width to auto
if ( p == 'height' || p == 'width' )
jQuery.setAuto( z.el, p );
}
}
}
// If a callback was provided, execute it
if( done && z.o.complete && z.o.complete.constructor == Function )
// Execute the complete function
z.o.complete.apply( z.el );
} else {
// Figure out where in the animation we are and set the number
var p = (t - this.startTime) / z.o.duration;
z.now = ((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum;
// Perform the next step of the animation
z.a();
}
};
}

先看fx,fx第一行代码 var z = this; 这里的this指针指向的是 new jQuery.fx产生的对象。接下来三行代码定义了z上的o属性(options)、z上的el属性(缓存elem引用)和y变量(缓存elem的style属性)。

接下来定义了z上的a函数。a函数主要实现通过指定的方法或者默认的方式设置特效作用的属性的值。

接下来在z.max 和 z.cur 用于获取当前元素指定的属性的最大值和现在的值。通过查找max和cur的调用位置可以看出两个函数的实现

z.custom相当于fx的核心、驱动器。因为我们在这里看到了window.setInterval(function,13)的代码。z.custom实现:记录当前的开始时间。设置z.now为from值。调用z.a()将z.now的值设置到元素上。开始触发器执行z.step()方法。为什么在开始触发器之前要调用一次z.a()呢?因为from的值可能不是元素当前的值嘛。

z.show 和 z.hide方法实现了对响应需要显示和隐藏的特效进行了封装,默认传递了一个为0的参数。并对旧的属性值进行了记录。刚开始我一下也没反映过来show和hide调用位置。在后面判断了z.o.hide,本来我还以为这俩方法没有被调用过的。直到我看了几遍判断z.o.hide的代码后觉得看看前面animate附近的代码定义时才发现对show和hide的调用位置。注意animate中代码实现判断p不为Number所执行的代码。

接下来是对ie的一个兼容处理和一个对overflow的处理,防止在特效时元素中的内容超出容器之外显示。

代码量稍多的step方法。获取当前时间。如果没有超出特效的执行时间那么进行下一步特效,计算下一步的值并设置属性值。如果超出了特效执行时间停止触发器,清理timer,将z.now设置为最终值并调用z.a()设置到元素属性上。设置z.el.curAnim[prop] = true 标记对此属性的特效已完成。这里要注意到当对el一次特效处理设置了多个属性时,会每个属性产生一个z(jQuery.fx对象实例),所有z上的el都是同一个,这也表明每个z处理一个单一的属性。检查是否真的完成所有属性的特效处理。如果完成了所有的特效处理还原overflow属性,如果是hide特效则在第一次if检查时设置display属性为none,第二次if检查时将元素的特效属性的原值设置回去。如果完成了特效处理同时设置了回调函数则执行回调函数。

在最后完成时检查z.o.hiden为啥要写两个一样的if呢?