2016-02-25 65 views
2

我試圖讓一個功能,將不斷淡入和淡出隨機選擇的圖片,以便相同的圖片不會出現兩次。我可以得到它的淡出/改變圖像/如果點擊與連續淡入和淡出隨機圖片

$("img").click(function() { CODE }); 

一度淡出,但我必須點擊圖像的每個時間,我陷入試圖使之成爲一個功能是當頁面加載叫:

$(document).ready(function() { 
    $("img").fadeOut(2000, function() { 
    while (picPicker1 === picPicker2) { 
     picPicker2 = (Math.floor(Math.random() * 5) - 1); 
    } 

    var source = pics[picPicker2]; 
    $("img").attr("src", source); 
    $("img").fadeIn(2000); 
    picPicker1 = picPicker2; 
    }); 
}); 

pics[]是用五種不同的圖片網頁地址的數組。我也試過使用setInterval,但那也沒用。所有這些語言都是新手,所以請提前感謝您的耐心等待!

+1

看那'的setInterval()'js函數。 – magreenberg

回答

1

setInterval是正確的功能使用。您在問題中提供的代碼缺少關閉});

下面是一些基本的代碼,使用的setInterval改變形象:

JQuery的:

var pics = [ 
    "https://placehold.it/350x150/ff0000", 
    "https://placehold.it/350x150/00ff00", 
    "https://placehold.it/350x150/0000ff", 
    "https://placehold.it/350x150/F2F5A9", 
    "https://placehold.it/350x150/FF00FF", 
]; 

setInterval(function() { 
    var picPicker2 = (Math.floor(Math.random() * 5) + 1); 

    var source = pics[picPicker2]; 
    $("img").fadeOut(500).attr("src", source).fadeIn(500); 
}, 2000); 

注:圖像將重複偶爾,但代碼我提供只是你改進的基礎。

Fiddle Demo

0

您可以使用setInterval()for (x = 5; x > 0; x ++) {},var x = 0; do {} while (x = 0);var x = 0; while (x = 0) {}

0

$(document).ready(function() { 
 
    var picPicker, source; 
 

 
\t function generateImage() { 
 
    $("img").fadeOut(2000, function() { 
 
    picPicker = (Math.floor(Math.random() * 200)); 
 

 
    source = 'https://unsplash.it/400/300/?image=' + picPicker; 
 
\t \t 
 
    $("img").attr("src", source); 
 
    $("img").fadeIn(2000); 
 
    }); 
 
    
 
    setTimeout(generateImage, 5000); 
 
} 
 
    
 
generateImage(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<img src="https://unsplash.it/400/300/?image=1">