h5手机摇一摇

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>摇一摇</title>
</head>

<body>
<div>
摇一摇
</div>
<script>
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
} else {
alert('您的设备不支持该功能');
}
var SHAKE_THRESHOLD = 800;
var last_update = 0;
var x, y, z, lastX, lastY, lastZ;
var count = 0;
var lock = true;

function deviceMotionHandler(eventData) {
var acceleration = eventData.accelerationIncludingGravity;
var curTime = new Date().getTime();
if ((curTime - last_update) > 300 && lock) {
var diffTime = curTime - last_update;
last_update = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
lock = false;
setTimeout(function () {
lock = true;
}, 2000)
navigator.vibrate(1000)
alert(count++);
}
lastX = x;
lastY = y;
lastZ = z;
}
 
}
</script>
</body>

</html>
posted @ 2018-12-10 14:10  码路上的奋斗  阅读(196)  评论(0编辑  收藏  举报