10
如何利用新的MobileSafari設備運動API捕捉「搖晃」事件?在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);
}
優秀。感謝您添加代碼提取。應該有幫助! – tbeseda 2010-12-17 22:33:50
只是一個警告:accelerationIncludingGravity將永遠不會有所有三個組件零。如果重力直接作用於一個軸,則該軸的值將爲9.81。另外,爲什麼不在活動中檢查震動,而不是在間隔中檢查? – ughoavgfhw 2010-12-17 22:39:30
@ughoavgfhw你能提出一段代碼嗎? – andi 2013-04-10 10:25:43