html5实现摇一摇功能
不废话,直接看实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
if (window.DeviceMotionEvent) { window.addEventListener('devicemotion',deviceMotionHandler, false); } var speed = 30;//控制摇一摇的速度 var x = y = z = lastX = lastY = lastZ = 0; function deviceMotionHandler(eventData) { var acceleration =event.accelerationIncludingGravity; x = acceleration.x; y = acceleration.y; z = acceleration.z; if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed || Math.abs(z-lastZ) > speed) { //这里写你的业务逻辑 alert(1); } lastX = x; lastY = y; lastZ = z; } |