首先對DeviceMotionEvent進(jìn)行優(yōu)化;
去除無用的代碼,重新封裝DeviceMotionEven
if(window.DeviceMotionEvent) {
var speed = 25;//定義一個(gè)數(shù)值
var x = y = z = lastX = lastY = lastZ = 0;//重置所有數(shù)值
window.addEventListener('devicemotion', function(){
var acceleration =event.accelerationIncludingGravity;//將傳感值賦給acceleration
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed ) {
// TODO:在此處可以實(shí)現(xiàn)搖一搖之后所要進(jìn)行的數(shù)據(jù)邏輯操作
donghua();
}
lastX = x;
lastY = y;
lastZ = z;
}, false);
}
由于實(shí)際項(xiàng)目中有很多需求無法很好的實(shí)現(xiàn),
比如:動畫不執(zhí)行完畢就不能繼續(xù)執(zhí)行DeviceMotionEvent事件;
所以做了進(jìn)一步優(yōu)化;
var f=1;
function donghua(){
//動畫事件
$(".img").animate({left:'0',opacity:'1'},700,function(){f=1;});
});
if(window.DeviceMotionEvent) {
var speed = 25;//定義一個(gè)數(shù)值
var x = y = z = lastX = lastY = lastZ = 0;//重置所有數(shù)值
window.addEventListener('devicemotion', function(){
var acceleration =event.accelerationIncludingGravity;//將傳感值賦給acceleration
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed ) {
// TODO:在此處可以實(shí)現(xiàn)搖一搖之后所要進(jìn)行的數(shù)據(jù)邏輯操作
if(f==1){
donghua();
f=0;
}
}
lastX = x;
lastY = y;
lastZ = z;
}, false);
}
現(xiàn)在就完美了