Javascript网页摇一摇功能(转:http://www.cnblogs.com/LoveOrHate/p/4471348.html)
function(){ if(window.DeviceMotionevent){ //移动浏览器支持运动传感事件 window.addEventListener('devicemotion',deviceMotionHandler,false); } } var SHAKE_THRESHOLD=0; //定义一个变量保存上次更新的时间 var last_update=0; //紧接着定义x,y,z记录三个轴的数据以及上一次出发时间 var x,y,z,last_x,last_y,last_x,count=0; function deviceMotionHandler(eventData){ //获取含重力的加速度 var acceleration=eventData.accelerationIncludingGravity; //获取当前时间 var curTime=new Date().getTime(); var diffTime=curtime-last_update; //固定时间 if(diffTime>100){ last_update=curTime; x=acceleration.x; y=acceleration.y; z=acceleration.z; var speed=Math.abs(x+y+z-last_x-last_y-last_z)/difftime*30000; if(speed>SHAKE_THRESHOLD){ //此处可以实现摇一摇之后所要进行的数据逻辑操作 } //记录上一次加速度 last_x=x; last_y=y; last_z=z; } }
HTML5晃动DeviceMotionEvent事件
deviceMotionHandler//运动传感处理
last_update=curtime//记录上一次摇动的时间
x=acceleration.x//获取加速度x方向
y=acceleration.y//获取加速度y方向
z=acceleration.z//获取加速度垂直方向
if(speed>SHAKE_THRESHOLD){
//做你想做的事...
}
最后你可以这样调用的哟!!!!
<script>
$(doucment).ready(function(){
init();
});
</script>

浙公网安备 33010602011771号