shake.html 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>摇一摇</title>
  8. </head>
  9. <body>
  10. <div>
  11. 摇一摇
  12. </div>
  13. <script>
  14. const SHAKE_SPEED = 300;
  15. let lastTime = 0;//上次变化的时间
  16. let x = y = z = lastX = lastY = lastZ = 0;//位置变量初始化
  17. function motionHandler(event) {
  18. let acceleration = event.accelerationIncludingGravity;
  19. let curTime = Date.now();//取得当前时间
  20. if ((curTime - lastTime) > 120) {
  21. let diffTime = curTime - lastTime;
  22. lastTime = curTime;
  23. x = acceleration.x;
  24. y = acceleration.y;
  25. z = acceleration.z;
  26. //计算摇动速度
  27. let speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 1000;
  28. if (speed > SHAKE_SPEED) {
  29. alert("你摇动了手机");
  30. }
  31. lastX = x;
  32. lastY = y;
  33. lastZ = z;
  34. }
  35. }
  36. if(window.DeviceMotionEvent) {
  37. window.addEventListener('devicemotion', motionHandler, false);
  38. } else {
  39. alert("你的设备不支持位置感应");
  40. }
  41. </script>
  42. </body>
  43. </html>