0

我正在尝试模仿 jQueryanimate()方法来去除opacity不受支持的浏览器(当然是 Internet Explorer)的样式!

但是,我正在努力模仿 jQueryanimate()方法接受的参数。

根据 jQuery 文档:

.animate( properties [, duration] [, easing] [, complete] )
.animate( properties, options )

我想知道的是函数如何知道参数2是持续时间还是选项......?

注意这里的三个参数:

$('#test').animate({opacity:0},200,function(){
    $(this).hide(); 
});

但我也可以像这样执行相同的函数(注意 easing 参数):

$('#test').animate({opacity:0},200,'swing',function(){
    $(this).hide(); 
});

函数怎么知道第三个参数是字符串,不是函数?

这肯定不是这样的吗????

if(typeof parameter1=='string'){
    // and so on
}
4

2 回答 2

2

Surely this is not done like so????

if(typeof parameter1=='string'){
    // and so on
}

Yes, that is exactly how it is done.


From the jQuery source:

var opt = speed && typeof speed === "object" ? jQuery.extend({},
speed) : {
    complete: fn || !fn && easing || jQuery.isFunction(speed) && speed,
    duration: speed,
    easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};

opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;

Can be rewritten to be more readable this way:

var opt = { };

if (typeof speed == 'object')
    opt = jQuery.extend({ }, speed);
else {

    if (fn)
        opt.complete = fn;
    else if (easing)
        opt.complete = easing;
    else if (jQuery.isFunction(speed))
        opt.complete = speed;

    opt.duration = speed;

    if (fn && easing)
        opt.easing = easing;
    else if (easing && !jQuery.isFunction(easing))
        opt.easing = easing;

}

if (jQuery.fx.off)
    opt.duration = 0;
else if (typeof opt.duration === 'number')
    opt.duration = opt.duration;
else if (opt.duration in jQuery.fx.speeds)
    opt.duration = jQuery.fx.speeds[opt.duration];
else
    opt.duration = jQuery.fx.speeds._default;

Update

If you want an easier way to take care of this logic for you, candy provides a neat Array helper called persuade. This function allows you to pass in an array (or arguments) object with a list of types. You will be returned an array with the arguments organized by the types. It's an easy way to deal with polymorphic parameters:

function foo(/* duration, easing, complete */) {
    var args = candy.Arrays.persuade(arguments, [ 'number', 'string', 'function' ]);
    var duration = args[0], easing = args[1], complete = args[2];
    console.log(duration, easing, complete);
}

foo('test');
// => undefined, 'test', undefined

foo(2, function() { });
// => 2, undefined, function() { }
于 2012-11-23T14:06:09.447 回答
1

我想知道的是函数如何知道参数2是持续时间还是选项......?

如果第二个参数是一个对象,那么它就是选项。如果它可以解析intduration. 如果是函数,则为callback,否则为easing

于 2012-11-23T14:00:05.717 回答