2010-12-17 10 views

Odpowiedz

18

Zobacz ten niesamowity blogu: http://www.jeffreyharrell.com/blog/2010/11/creating-a-shake-event-in-mobile-safari/

który ilustruje poniższy przykład:

if (typeof window.DeviceMotionEvent != 'undefined') { 
    // Shake sensitivity (a lower number is more) 
    var sensitivity = 20; 

    // Position variables 
    var x1 = 0, y1 = 0, z1 = 0, x2 = 0, y2 = 0, z2 = 0; 

    // Listen to motion events and update the position 
    window.addEventListener('devicemotion', function (e) { 
     x1 = e.accelerationIncludingGravity.x; 
     y1 = e.accelerationIncludingGravity.y; 
     z1 = e.accelerationIncludingGravity.z; 
    }, false); 

    // Periodically check the position and fire 
    // if the change is greater than the sensitivity 
    setInterval(function() { 
     var change = Math.abs(x1-x2+y1-y2+z1-z2); 

     if (change > sensitivity) { 
      alert('Shake!'); 
     } 

     // Update new position 
     x2 = x1; 
     y2 = y1; 
     z2 = z1; 
    }, 150); 
} 
+2

Doskonałe. Dziękujemy za dodanie wyciągu z kodu. Powinien być pomocny! – tbeseda

+3

Po prostu ostrzeżenie: Acceleration IncludingGravity nigdy nie będzie mieć wszystkich trzech składników zero. Jeśli grawitacja działa bezpośrednio na jednej osi, oś ta będzie miała wartość 9,81. Dlaczego nie sprawdzać wstrząsów podczas wydarzenia, a nie w interwale? – ughoavgfhw

+0

@ughoavgfhw czy mógłbyś zaproponować swój kawałek kodu? – andi