html5摇一摇代码优化包括DeviceMotionEvent等等
程序员文章站
2023-11-05 23:23:52
对DeviceMotionEvent进行优化,除无用的代码重新封装DeviceMotionEven,另外动画不执行完毕就不能继续执行DeviceMotionEvent事件,所以这点也要进行优化... 14-09-01...
首先对devicemotionevent进行优化;
去除无用的代码,重新封装devicemotioneven
if(window.devicemotionevent) {
var speed = 25;//定义一个数值
var x = y = z = lastx = lasty = lastz = 0;//重置所有数值
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:在此处可以实现摇一摇之后所要进行的数据逻辑操作
donghua();
}
lastx = x;
lasty = y;
lastz = z;
}, false);
}
由于实际项目中有很多需求无法很好的实现,
比如:动画不执行完毕就不能继续执行devicemotionevent事件;
所以做了进一步优化;
var f=1;
function donghua(){
//动画事件
$(".img").animate({left:'0',opacity:'1'},700,function(){f=1;});
});
if(window.devicemotionevent) {
var speed = 25;//定义一个数值
var x = y = z = lastx = lasty = lastz = 0;//重置所有数值
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:在此处可以实现摇一摇之后所要进行的数据逻辑操作
if(f==1){
donghua();
f=0;
}
}
lastx = x;
lasty = y;
lastz = z;
}, false);
}
现在就完美了
去除无用的代码,重新封装devicemotioneven
复制代码
代码如下:if(window.devicemotionevent) {
var speed = 25;//定义一个数值
var x = y = z = lastx = lasty = lastz = 0;//重置所有数值
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:在此处可以实现摇一摇之后所要进行的数据逻辑操作
donghua();
}
lastx = x;
lasty = y;
lastz = z;
}, false);
}
由于实际项目中有很多需求无法很好的实现,
比如:动画不执行完毕就不能继续执行devicemotionevent事件;
所以做了进一步优化;
复制代码
代码如下:var f=1;
function donghua(){
//动画事件
$(".img").animate({left:'0',opacity:'1'},700,function(){f=1;});
});
if(window.devicemotionevent) {
var speed = 25;//定义一个数值
var x = y = z = lastx = lasty = lastz = 0;//重置所有数值
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:在此处可以实现摇一摇之后所要进行的数据逻辑操作
if(f==1){
donghua();
f=0;
}
}
lastx = x;
lasty = y;
lastz = z;
}, false);
}
现在就完美了
上一篇: Servlet与JSP间的两种传值情况