我在學習JavaScript,我的一個練習是將框從左向右移動。它在最初的幾個週期內工作良好,但隨後變得混亂,我不知道是什麼原因造成的。我嘗試從左向右移動框,然後再次移動,但在幾個週期後崩潰
function preparePage(){
var box = document.getElementById("box");
var leftPosition = 0;
box.style.position = "absolute";
function animateRight(){
leftPosition += 1;
if (leftPosition<=300){
box.style.left = leftPosition+"px";
} else {
console.log("leftPosition = ",leftPosition);
clearInterval(intervalRight);
intervalLeft = setInterval(animateLeft, 20);
}
}
function animateLeft(){
if (leftPosition>=0){
leftPosition -=1;
box.style.left = leftPosition+"px";
} else {
console.log("leftPosition =", leftPosition);
clearInterval(intervalLeft);
setInterval(animateRight,20);
}
}
intervalRight = setInterval(animateRight,20);
}
window.onload = function(){
preparePage();
}
定義 「它就會變得混亂」。 – Toomai
[這是完整的代碼](http://pastebin.com/e9keWpEV)。起初,當它向左移動時它開始移動得更快,然後它從一側跳到另一側,遠遠超過預期的300像素。 – pumpalarumpa