DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> HTML基礎知識 >> HTML5教程 >> html5搖一搖代碼優化包括DeviceMotionEvent等等
html5搖一搖代碼優化包括DeviceMotionEvent等等
編輯: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);
}


現在就完美了 

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved