日期:2014-05-16 浏览次数:20697 次
此功能通过html5新特性重力加速实现,不多说,上代码:
<html> <head> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0,user-scalable=no" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>摇一摇,送妹子</title> </head> <body> <div id="shake" style="font-size: 14px; margin: 10px; line-height: 35px; display: none;"></div> <script type="text/javascript"> //需要判断浏览器是否支持 if (window.DeviceMotionEvent) { window.addEventListener('devicemotion', deviceMotionHandler, false); document.getElementById("shake").innerHTML = '摇一摇,送“妹子”。'; } else{ document.getElementById("shake").innerHTML = '您看到了以下提示,说明您现在还不支持摇一摇功能。'; } var SHAKE_THRESHOLD = 3000;//摇动的阀值 var lastUpdate = 0;//变量保存上次更新的时间 var x, y, z, last_x, last_y, last_z;// x、y、z记录三个轴的数据以及上一次出发的时间 var count = 0;//计数器 function deviceMotionHandler(eventData) { var acceleration = eventData.accelerationIncludingGravity;// 获取含重力的加速度 var curTime = new Date().getTime();// 获取当前时间 var diffTime = curTime -lastUpdate;//时间差 // 固定时间段 if (diffTime > 100) { lastUpdate = curTime; x = acceleration.x; y = acceleration.y; z = acceleration.z; var speed = Math.abs(x+y+z-last_x-last_y-last_z) / diffTime * 10000;//速度 // document.getElementById("shake").innerHTML = document.getElementById("shake").innerHTML + "<br />" + speed; //在阀值内 if(speed > SHAKE_THRESHOLD){ count++; alert('摇的很给力,送个妹子给你。'); document.getElementById("shake").innerHTML += "<br />" + "已送你(" + count + ")个妹子!"; } last_x = x; last_y = y; last_z = z; } } document.getElementById("shake").style.display = 'block'; </script> </body> </html>