0
我已經通過一個精靈表寫了一個小功能循環。在函數中,我有一個settimeout循環遍歷幀。在最後一幀時,超時被清除,計數器被設置爲零 - 並且動畫再次開始。的Javascript setTimeout的範圍引用錯誤的變量
這對一個動畫效果很好,但是當我嘗試並調用很多動畫時 - 它們都開始但是無法循環,除了designSprite,它很快樂地循環。我打電話給designSprite anim last ....
所以我猜這個問題是由於變量被覆蓋,當我調用一個新的功能實例 - setTimeOut引用新變量?我迷惑了自己。我試圖修復它,但仍然失敗。
感謝, 羅布
// Arrays to hold our sprite coordinates.
var animationSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
var mediaSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
var filmSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
var designSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
// call the loopAnim function, passing in the sprite array, and id of the div
loopAnim(animationSprite ,'#animationFrame')
loopAnim(mediaSprite ,'#mediaFrame')
loopAnim(filmSprite ,'#filmFrame')
loopAnim(designSprite ,'#designFrame')
function loopAnim(sprite , frameID) {
var totalFrames = sprite.length; // count how many 'frames' are in our sprites array.
var count = 0; // set up a basic counter to count which frame we're on.
var theLoop = function(){
// Move the background position of our frame by reading the X & Y co-ordinates from the sprites array.
$(frameID).css("background-position" , sprite[count].X + "px " + sprite[count].Y + "px");
count++; // increment the frame by 1 on each loop
// if count is LESS than total number of frames, set a timeout to keep running the "theLoop" function
if (count < totalFrames){
setAnim = setTimeout(theLoop, 60);
// if count is greater than the total number of frames - clear our timeout. Reset the counter back to zero, and then run our loop function again
} else {
clearTimeout(setAnim);
count = 0;
theLoop();
}
}
theLoop();
}
我是個白癡......我剛剛浪費了一個小時的最好的部分試圖捉摸,一出... ARRGGGHHH!感謝您的幫助:) – Rob
@Rob JavaScript編程的樂趣:)一個建議:我強烈建議在代碼中使用「use strict」。它有助於捕捉像這樣的東西。 – tsherif