2013-04-01 83 views
1

我有這樣的腳本:jQuery的變化圖像

<script> 
var images = [ 
    "webit.png", 
    "analog.png", 
    "projectica.png" 
]; 

currentImage = 0; 

function ChangeImage() 
{ 
    currentImage++; 

    if (currentImage > images.length - 1) 
     currentImage = 0; 
    $("#screenBackImage").css("background-image", "url(images/works/" + images[currentImage] + ")"); 

    $("#screenImage").fadeOut(500, function() { 
     $("#screenImage").attr("src", "images/works/" + images[currentImage]); 
     $("#screenImage").fadeIn(500); 
    }); 
    setTimeout(function() { 
     ChangeImage(); 
    }, 5000); 
} 

ChangeImage(); 
</script> 

當在第一時間的圖像變化,這是跳過圖像陣列中的第二圖像,以「projectica.png」,然後到在陣列中的第一個圖像,然後它的工作良好(第一,第二,第三,再次第一..),

這是爲什麼發生?

+0

你說的意思是什麼「那麼它的工作好」?並注意你從數組中的第二個圖像開始(數字從0開始),隨着您在開始時增加 – pfried

回答

2

您使用數組的第二個索引通過增加索引變量通過currentImage++;初始化currentImage到-1會做的伎倆爲您第一時間的問題,你會被currentImage++;

獲得零指數(第一要素更改

currentImage = 0; 

currentImage = -1; 

您的代碼將

var images = [ 
    "webit.png", 
    "analog.png", 
    "projectica.png" 
]; 

currentImage = -1; 

function ChangeImage() 
{ 
    currentImage++; 

    if (currentImage > images.length - 1) 
     currentImage = 0; 
    $("#screenBackImage").css("background-image", "url(images/works/" + images[currentImage] + ")"); 

    $("#screenImage").fadeOut(500, function() { 
     $("#screenImage").attr("src", "images/works/" + images[currentImage]); 
     $("#screenImage").fadeIn(500); 
    }); 
    setTimeout(function() { 
     ChangeImage(); 
    }, 5000); 
} 

ChangeImage(); 
1

我認爲你應該這樣做:

if (currentImage > images.length - 1) currentImage = 0; 
$("#screenBackImage").css("background-image", "url(images/works/" + images[currentImage] + ")"); 

$("#screenImage").fadeOut(500, function() { 
    $("#screenImage").attr("src", "images/works/" + images[currentImage]); 
    $("#screenImage").fadeIn(500); 
}); 

// Increment the currentImage variable here, not in the begining... 
currentImage++; 

DEMO HERE