Come posso utilizzare il tempismo javascript per controllare gli eventi di arresto del mouse e di spostamento del mouse

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

  •  03-07-2019
  •  | 
  •  

Domanda

Quindi ho un controllo (una mappa) su una pagina aspx. Voglio scrivere un po 'di javascript per caricare l'installazione come segue:

  1. quando il mouse si ferma su control = un po 'di codice

  2. quando il mouse si sposta = un po 'di codice (ma solo se lo spostamento è più lungo di 250 mil sec)

Funziona per attivare il codice in stop e poi in 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
    }, thread;

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

Ma non riesco a capire come introdurre un ritardo nel codice di spostamento. Pensavo di averlo avuto con questo ...

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);
    };
    })();
};

Ma non si comporta come pensavo. L'opzione "sposta2" thread2 " non viene mai cancellato dallo stop. Cosa mi sto perdendo?

È stato utile?

Soluzione

È difficile. Un po 'di armeggiamento ha portato a questo:

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
    };

  })();

};

Il motivo per cui il tuo codice non funziona è che mousemove si attiva ripetutamente mentre il mouse si sposta e stai iniziando nuovi timeout ogni volta.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top