首页 > 代码库 > html5摇一摇代码优化

html5摇一摇代码优化

首先对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);
}
如今就完美了



html5摇一摇代码优化