0

要素の位置に応じていくつかの機能をトリガーしたいと思います。この要素の位置は10秒ごとに変わります。トリガーする関数は20個あります。

私はこの擬似コードについて考えました:

When element position changes{
  Loop through all the coordinates to see if a function can be triggered{
     if the current element position matches the function's triggering position 
         execute the function
     }
}

ただし、1秒ごとに可能なすべての位置をループすると、ブラウザに負担がかかります。したがって、それを行うためのイベントを開催する方法がある場合。

出来ますか ?

編集:ビートルート-ビートルートのコメントの後、移動する要素はX横座標でのみ移動する、つまり1次元だけであると言わなければなりません。

これは、左から右に移動する水平方向のタイムラインによく似ており、特定の年に達するとアニメーションが発生します。ただし、移動速度はユーザーが上げることができるため、アニメーションをトリガーする固定時間はオプションではありません。

4

1 に答える 1

2

あなたが望むものを達成する方法はたくさんあるはずです。以下のコードは、カスタム イベントを処理する jQuery の機能を利用して、"疎結合" オブザーバー パターンを提供します。

$(function() {

    //Establish the two dozen functions that will be called.
    var functionList = [
        function() {...},
        function() {...},
        function() {...},
        ...
    ];

    var gridParams = {offset:10, pitch:65};//Example grid parameters. Adjust as necessary.

    //Establish a custom event and its handler.
    var $myElement = $("#myID").data('lastIndex', -1).on('hasMoved', function() {
        $element = $(this);
        var pos = $element.position();//Position of the moved element relative to its offset parent.
        var index = Math.floor((pos.left - gridParams.offset) / gridParams.pitch);//Example algorithm for converting pos.left to grid index.
        if(index !== $element.data('lastIndex')) {//Has latest movement align the element with the next grid cell?
            functionList[index](index, $element);//Call the selected function.
            $element.data('lastIndex', index);//Remember index so it can be tested mext time.
        }
    });
});

$(function() {
    //(Existing) function that moves the element must trigger the custom 'hasMoved' event after the postition has been changed.
    function moveElement() {
        ...
        ...
        ...
        myElement.trigger('hasMoved');//loosely coupled 'hasMoved' functionality.
    }

    var movementInterval = setInterval(moveElement, 100);
});

ご覧のとおり、疎結合の利点は、関数とそれを呼び出すコードが異なるスコープにある可能性があり.on('hasMoved', function() {...}myElement.trigger('hasMoved')異なる$(function(){...})構造にあることです。

他の関数を追加して位置を変更したい場合myElement(例: first、previous、next、last 関数)、要素を移動した後、それらは単に「hasMoved」をトリガーして、2 つのうちの適切な 1 つが確実に移動されるようにする必要があります。スコープを気にする必要なく、多数の関数が呼び出されます。

確認する必要がある唯一のことは、カスタム イベント ハンドラーによって呼び出すことができるように、20 個の関数のスコープが設定されていることです (つまり、グローバル スコープまでの同じスコープまたは外側のスコープ内にある)。

私は多くの仮定をしなければならなかったので、上記のコードは 100% 正しいわけではありませんが、うまくいけば先へ進む道を提供してくれるでしょう。

于 2012-09-10T11:36:56.260 に答える