2013-10-10 51 views
0

我有兩個羣體有以下模式命名的圖像:切換和褪色的圖像組中

Oranges1.jpg Oranges2.jpg Oranges3.jpg Oranges4.jpg

Apples1.jpg Apples2 .JPG Apples3.jpg Apples4.jpg

在我的網頁我有一個顯示從每個組選擇圖像的一個div:

<div> 
<img src="Oranges1.jpg"/> 
<img src="Oranges2.jpg"/> 
<img src="Apples3.jpg"/> 
<img src="Apples4.jpg"/> 
</div> 

我想通過jQuery來做的是切換和淡入淡出兩組之間的圖像。例如,當頁面將圖像加載到負載以上時。然後,5秒後,將圖像組切換,所以 「Oranges1.jpg」 變成 「Apples1.jpg」, 「Apples3.jpg」 變成 「Oranges3.jpg」 等如:

<div> 
<img src="Apples1.jpg"/> 
<img src="Apples2.jpg"/> 
<img src="Oranges3.jpg"/> 
<img src="Oranges4.jpg"/> 
</div> 

所以,每5秒圖像變成相反的組,但是具有相應的圖像編號。

有關最佳方法的任何想法?

謝謝!

+0

'setInterval()'和'.replace()'用於jquery。 – Jai

回答

1

嘗試這樣:

setTimeout(function() { 
$('div img').each(function() { 
    if ($(this).prop('src').indexOf('Oranges') != -1) 
     $(this).prop('src', $(this).prop('src').replace('Oranges', 'Apples')); 

    if ($(this).prop('src').indexOf('Apples') != -1) 
     $(this).prop('src', $(this).prop('src').replace('Apples', 'Oranges'));     
}); 
}, 5000) 
+0

謝謝,看到我對Spokey的回答所做的評論,因爲我結合了你的兩個例子。 – ca8msm

1
setInterval(function(){ 
    $('div > img').each(function(i){ 
     this.src = (/Apples/g.test(this.src) ? 'Oranges' : 'Apples') 
      + (i+1) + '.jpg'; 
    }); 
}, 5000); 

FIDDLE

+0

非常好,謝謝。我結束了與你和LorDex的例子的混合物,以防萬一網址中有絕對路徑: – ca8msm

+0

setInterval(function(){ $('div> img')。each(function(i){ this.src =(/apples/g.test(this.src)?$(this).prop('src')。replace('apples','oranges'):$(this).prop('src')。replace ('oranges','apples')); }); },5000); – ca8msm

0

的格式沒有在評論中走出來的非常好,但是兩個答案的組合意味着我有去:

setInterval(function(){ 
    $('div > img').each(function(i){ 
     this.src = (/apples/g.test(this.src) ? $(this).prop('src').replace('apples', 'oranges') : $(this).prop('src').replace('oranges', 'apples')); 
    }); 
}, 5000); 

感謝你們兩位!