0

サポートされていないブラウザ(もちろんInternet Explorer)animate()のスタイルを取り除くために、jQueryメソッドを模倣しようとしています!opacity

ただし、jQueryanimate()メソッドが受け入れるパラメーターを模倣するのに苦労しています。

jQueryのドキュメントによると:

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

私が知りたいのは、関数がパラメーター2が期間であるかオプションであるかをどのように知るかです...?

ここで3つの引数に注意してください。

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

しかし、私はこのような同じ関数を実行することもできます(イージングパラメーターに注意してください):

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

関数は、3番目のパラメーターが関数ではなく文字列であることをどのように認識しますか?

確かにこれはそのように行われていませんか????

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

2 に答える 2

2

確かにこれはそのように行われていませんか????

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

はい、それはまさにそれが行われる方法です。


jQueryソースから:

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;

このように読みやすくするために書き直すことができます。

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;

アップデート

このロジックをより簡単に処理する方法が必要な場合は、candyが。と呼ばれるきちんとしたアレイヘルパーを提供しますpersuade。この関数を使用すると、型のリストを含む配列(またはarguments)オブジェクトを渡すことができます。タイプごとに整理された引数を持つ配列が返されます。これは、多態的なパラメータを処理する簡単な方法です。

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が期間であるかオプションであるかをどのように知るかです...?

2番目のパラメーターがオブジェクトの場合、それはオプションです。に解析できる場合はintdurationです。関数の場合callbackは、、それ以外の場合はeasing

于 2012-11-23T14:00:05.717 に答える