javascriptタイミングを使用して、マウスの停止およびマウスの移動イベントを制御する方法

StackOverflow https://stackoverflow.com/questions/219322

  •  03-07-2019
  •  | 
  •  

質問

つまり、aspxページにコントロール(マップ)があります。次の設定をオンロードするJavaScriptを作成します。

  1. コントロールでマウスが停止したとき=コード

  2. マウスの動き=何らかのコード(ただし、動きが250ミリ秒より長い場合のみ)

これは、停止してから移動するときにコードをトリガーするように機能します...

function setupmousemovement() {
var map1 = document.getElementById('Map_Panel');
var map = document.getElementById('Map1');
map1.onmousemove = (function() {
    var onmousestop = function() {
            //code to do on stop
    }, thread;

    return function() {
        //code to do on mouse move
        clearTimeout(thread);
        thread = setTimeout(onmousestop, 25);
    };
    })();
};

しかし、on moveコードに遅延を導入する方法はわかりません。私はこれでそれを持っていると思った...

function setupmousemovement() {
var map1 = document.getElementById('Map_Panel');
var map = document.getElementById('Map1');
map1.onmousemove = (function() {
    var onmousestop = function() {
            //code to do on stop
            clearTimeout(thread2);
    }, thread;

    return function() {
        thread2 = setTimeout("code to do on mouse move", 250);
        clearTimeout(thread);
        thread = setTimeout(onmousestop, 25);
    };
    })();
};

しかし、思ったようには動作しません。移動中" thread2"ストップによってクリアされることはありません。何が足りないのですか?

役に立ちましたか?

解決

これは注意が必要です。少し手を加えた結果、次のようになりました。

function setupmousemovement() {

  var map1 = document.getElementById('Map_Panel');
  map1.onmousemove = (function() {
    var timer,
        timer250,
        onmousestop = function() {

          // code to do on stop

          clearTimeout( timer250 ); // I'm assuming we don't want this to happen if mouse stopped
          timer = null;  // this needs to be falsy next mousemove start
        };
    return function() {
      if (!timer) {

        // code to do on start

        timer250 = setTimeout(function () { // you can replace this with whatever

          // code to do when 250 millis have passed

        }, 250 );
      }
      // we are still moving, or this is our first time here...
      clearTimeout( timer );  // remove active end timer
      timer = setTimeout( onmousestop, 25 );  // delay the stopping action another 25 millis
    };

  })();

};

コードが機能しないのは、マウスの移動中にmousemoveが繰り返し起動し、毎回新しいタイムアウトを開始するためです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top