这就是我想要实现的目标:当用户摇动他的设备时,我希望页面上的元素在每次摇动时旋转CW 20度,当它达到最大45度时,每次摇动时CCW旋转20度,直到达到-45度,反之亦然。我正在使用“shake.js”来检测震动。问题是它是旋转,但不是动画。元素跳转到旋转度。所以我尝试使用for
循环setTimeout', I tried it with
而loop with setInterval and then I tried it with
setInterval`来实现动画效果,但我仍然无法实现动画效果。这是我的代码:
var maxDegree = 45;
var minDegree = -45;
var lastDegree = 0;
var totalShakes = 10;
var rotationDegree = 20;
var rotationCounter = 0;
var currentDegree = 0;
var shakeCounter = 0;
var direction = "right";
var box = null;
var info = null
var interval;
window.addEventListener('load', init, false);
function init() {
box = document.getElementById('box');
info = document.getElementById('tilt_info');
window.addEventListener('shake', shakeEventDidOccur, false);
}
function shakeEventDidOccur () {
shakeBox();
}
function shakeBox(){
if(direction == "right") {
currentDegree += rotationDegree;
if(currentDegree >= maxDegree) {
currentDegree = maxDegree;
direction = "left";
}
interval = setInterval(function(){
if(lastDegree < currentDegree){
box.style.webkitTransform = "rotateZ("+ (lastDegree++) +"deg)";
lastDegree++;
}
},100);
lastDegree = currentDegree;
} else {
//...the logic to rotate the box CCW
}
shakeCounter +=1;
info.innerHTML = shakeCounter;
if(shakeCounter >= totalShakes) {
box.style.webkitTransform = "rotateZ(0deg)";
window.removeEventListener('shake', shakeEventDidOccur, false);
}
}
这些是我之前谈到的循环:
for(var i = lastDegree; i <= currentDegree; i++) {
setTimeout(function(){
box.style.webkitTransform = "rotateZ("+ i +"deg)";
info.innerHTML = "LD: " + lastDegree + "; CD: " + currentDegree + "; i: " + i;
}, 1000);
}
while(lastDegree < currentDegree) {
setTimeout(){
function(){box.style.webkitTransform = "rotateZ("+ (lastDegree+1) +"deg)";
lastDegree++;}, 100
};
}
为什么我无法实现动画效果?