2012-08-13 55 views
1

幫助!我不知道這裏有什麼問題,我沿着來自Tuts +的教程視頻觀看。代碼是確切的,但藍色框並非左側動畫。不能使用Javascript動畫div #box

當我在moveBox函數內部發出警報時,我在控制檯中看到警報一遍又一遍地發出相同的消息。

這裏是我的測試環節:

> Trying to animation a blue box left using Javascript <

這裏是從視頻截圖:

enter image description here

這裏是我的代碼:

(function() { 

var speed = 10,  
    moveBox = function() { 
     var el = document.getElementById("box"), 
      i = 0, 
      left = el.offsetLeft, 
      moveBy = 3; 
      //console.log("moveBox executed " +(i+1)+ " times"); 

      el.style.left = left + moveBy + "px"; 

     if (left > 399) { 
      clearTimeout(timer); 
     } 
    }; 

var timer = setInterval(moveBox, speed); 

}()); 

HTML:

<!DOCTYPE html> 

<head> 
<meta charset="utf-8"> 
<title>JavaScript 101 : Window Object</title> 
<style> 
    #box { 
     position: abosolute; 
     height: 100px; 
     left: 50px; 
     top: 50px; 
     width: 100px; 
     background-color: Blue; 
    } 
</style> 
</head> 

<body> 

<div id="box"></div> 
<script src="js/animation.js"></script> 

回答

2

你在你的定位拼寫錯誤 「絕對」:

#box { 
    position: absolute; // Your mispelling here 
    height: 100px; 
    left: 50px; 
    top: 50px; 
    width: 100px; 
    background-color: Blue; 
} 

一旦我固定的,它工作得很好。

建議的一句話 - 在這樣的循環中放置第二個條件,以便動畫由於某種原因失敗時不會以無限循環結束。例如,你可能已經這樣做了:

(function() { 

var maxTimes = 1000; 
var loopTimes = 0; 
var speed = 10,  
moveBox = function() { 
    var el = document.getElementById("box"), 
     i = 0, 
     left = el.offsetLeft, 
     moveBy = 3; 
     //console.log("moveBox executed " +(i+1)+ " times"); 

    el.style.left = left + moveBy + "px"; 

    loopTimes += 1; 
    if (left > 399 || loopTimes > maxTimes) { 
     clearTimeout(timer); 
    } 
}; 

var timer = setInterval(moveBox, speed); 

}()); 
+0

謝謝! :D/facepalm – 2012-08-13 18:29:40

+0

不客氣!有時它只需要第二雙眼睛:-) – 2012-08-13 18:30:04