Home > Web Front-end > H5 Tutorial > HTML5 shake code optimization includes DeviceMotionEvent, etc._html5 tutorial skills

HTML5 shake code optimization includes DeviceMotionEvent, etc._html5 tutorial skills

WBOY
Release: 2016-05-16 15:47:23
Original
1479 people have browsed it

First optimize DeviceMotionEvent;

Remove useless code and repackage DeviceMotionEven

Copy code
code As follows:

if(window.DeviceMotionEvent) {
var speed = 25;//Define a value
var x = y = z = lastX = lastY = lastZ = 0;/ /Reset all values
window.addEventListener('devicemotion', function(){
var acceleration =event.accelerationIncludingGravity;//Assign the sensing value to acceleration
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed ) {
// TODO: Here you can implement the data logic operations to be performed after shaking
donghua();
}
lastX = x;
lastY = y;
lastZ = z ;
}, false);
}

Due to many requirements in actual projects that cannot be implemented well,

For example: the animation cannot continue until it is completed. Execute the DeviceMotionEvent event;

So further optimization has been done;

Copy the code
The code is as follows:

var f=1;
function donghua(){
//Animation event
$(".img").animate({left:'0',opacity:' 1'},700,function(){f=1;});
});
if(window.DeviceMotionEvent) {
var speed = 25;//Define a value
var x = y = z = lastX = lastY = lastZ = 0;//Reset all values ​​
window.addEventListener('devicemotion', function(){
var acceleration =event.accelerationIncludingGravity;//Will sense Values ​​assigned to acceleration
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
if(Math.abs(x-lastX) > speed || Math .abs(y-lastY) > speed ) {
// TODO: Here you can implement the data logic operations to be performed after shaking
if(f==1){
donghua( );
f=0;
}
}
lastX = x;
lastY = y;
lastZ = z;
}, false);
}

Now it’s perfect
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template