<script>
var switchDirection = false;
function doAnimation() {
var divAdvert = document.getElementById("divAdvert");
var currentLeft = divAdvert.offsetLeft;
var newLocation;
if (!switchDirection) {
newLocation = currentLeft + 2;
if (currentLeft >= 400) {
switchDirection = true;
}
} else {
newLocation = currentLeft - 2;
if (currentLeft <= 0) {
switchDirection = false;
}
}
divAdvert.style.left = newLocation + "px";
}
setInterval(doAnimation, 10);
</script>
我想知道爲什麼具有值爲false的新變量已在函數的開頭聲明。用true或false初始化一個變量是否在Javascript中建立了內容的方向?
...顯然將在函數中切換?請告訴我們你不明白的功能部分。 – Bergi 2015-04-02 04:50:43
var switchDirection = false;這個變量跟蹤內容當前的走向。如果switchDirection爲false,則內容從左向右移動,這是默認設置。如果switchDirection爲true,則內容從右向左移動。 //這是程序作者在解釋代碼時寫的內容。我不明白這一點,即如何將變量初始化爲false會使內容的方向從左向右。 - – 2015-04-02 19:05:18
這不是使div能夠做任何事情的變量的初始化。它是'doAnimation'函數,它使用'switchDirection'狀態來控制內容在當前步驟中移動的方向。 – Bergi 2015-04-02 20:11:07