手机摇一摇功能


// 首先在页面上要监听运动传感事件 
function init(){
  if (window.DeviceMotionEvent) {
    // 移动浏览器支持运动传感事件
    window.addEventListener('devicemotion', deviceMotionHandler, false);
  } else{

    alert("您的浏览器不支持摇一摇哦!");
  } 
}
function removeInit(){
window.removeEventListener('devicemotion', deviceMotionHandler, false);
}
// 首先,定义一个摇动的阀值
var SHAKE_THRESHOLD = 3000;
// 定义一个变量保存上次更新的时间
var last_update = 0;
// 紧接着定义x、y、z记录三个轴的数据以及上一次出发的时间
var x;
var y;
var z;
var last_x;
var last_y;
var last_z;

// 为了增加这个例子的一点无聊趣味性,增加一个计数器
var 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 * 10000; 

    if (speed > SHAKE_THRESHOLD){ 
if($('#animbg').hasClass('ani')){
$('.page5 .conPic img').attr('src',product[index].img);
$('.page5 .titleBtn img').attr('src',titleBtn[index].img);
     $('.page4').fadeOut();
     $('.page5').fadeIn();
     $('.page5').addClass('ani');
     // $('.page5 .conPic').html("<img src='"+product[index].img+"'>");
    
     }else{
     // alert("亲,请先添加婴幼儿专用水哦!");
     }

    }
    last_x = x; 
    last_y = y; 
    last_z = z; 
  } 

posted @ 2016-03-11 16:53  duowen  阅读(99)  评论(0编辑  收藏  举报