在iOS Safari中使用Javascript检测抖动?

问题描述:

如何利用新的MobileSafari设备运动API捕捉“摇晃”事件?在iOS Safari中使用Javascript检测抖动?

看到这个真棒博客文章:http://www.jeffreyharrell.com/blog/2010/11/creating-a-shake-event-in-mobile-safari/

这说明这个例子:

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

优秀。感谢您添加代码提取。应该有帮助! – tbeseda 2010-12-17 22:33:50

+3

只是一个警告:accelerationIncludingGravity将永远不会有所有三个组件零。如果重力直接作用于一个轴,则该轴的值将为9.81。另外,为什么不在活动中检查震动,而不是在间隔中检查? – ughoavgfhw 2010-12-17 22:39:30

+0

@ughoavgfhw你能提出一段代码吗? – andi 2013-04-10 10:25:43