0

HTML、CSS、Javascript を使用してアニメーション シーンを作成しています。現在、アニメートしたい魚ごとに 2 つの関数があります。1 つ目は画面全体に送信し、2 つ目は画面から外れたら位置をリセットします。

2つの機能は次のようになります...

function fish1Swim1() {
    var ranNum = Math.round(Math.random() * 2.5);
    var speed = 6000 * ranNum;
    var screenW = screenWidth+350;
    $('#fish1').animate({
        left: -screenW,
    }, speed, function () {
        fish1Swim2();
    });
}

function fish1Swim2() {
    var ranNum = Math.round(Math.random() * 7);
    var top = ranNum * 100;
    var screenW = screenWidth+350;
    $('#fish1').css("left", screenW);
    $('#fish1').css("top", top);
    fish1Swim1();
}

シーン内の他のすべての魚にも非常によく似た関数を使用していますが、スクリプトの最初に 2 つの配列を作成したいと思います。1 つは ID 用で、もう 1 つは速度用です...

var fish=["#fish1","#fish2","#oldBoot"];
var speeds=["6000","7000","5000"];

次に、先ほど書いた関数を実行しますが、fish と speed を配列の項目に置き換えます。

これどうやってするの?

4

1 に答える 1

1

どうですか?これにより、すべてのアニメーション/CSS の動きに対して一般化された機能が提供されます。アニメーションに関しては、必要に応じて速度が配列から読み取られます。

この関数には 2 つの引数が必要です。最初の引数は要素の ID (マイナス #) です。2 つ目はフェーズです (元のコードと同様に、フィッシュ 1 にはフェーズ 1 関数があり、フィッシュ 1 にはフェーズ 2 関数がありました)。

この関数を他のアニメーション要素で機能させるには、switch ステートメントを拡張するだけです。

//element data and corresponding anim speeds
var speeds = {fish1: 6000, fish2: 7000, oldBoot: 5000};

//main animation/movement func
function do_action(id, phase) {

    var el, jq_method, method_data, after;

    //work out what it is we're doing, and to what, and set some details accordingly
    switch (id) {
        case 'fish1':
            el = $('#fish1');
            switch (phase) {
                case 1:
                    jq_method = 'animate';
                    method_data = [
                        {left: -screenWidth+350},
                        Math.round(Math.random() * 2.5) * speeds[id],
                        function() { do_action('fish1', 2); }
                    ];
                    break;
                case 2:
                    jq_method = 'css';
                    method_data = [
                        {top: Math.round(Math.random() * 700), left: screenWidth+350}
                    ];
                    after = function() { do_action('fish1', 1); };

                break;
            }
            break;
        break;
    }

    //do actions
    el[jq_method].apply(el, method_data);
    if (after) after();

}

//and off we go
do_action('fish1', 1);
于 2012-07-12T15:53:47.253 に答える