2016-09-17 21 views
0

我想要11個圖像淡入淡出。我將它們存儲在一個數組中,並希望逐個循環,並在一個div中顯示它們。但它只顯示陣列中最後一個圖像11次。請指向正確的方向。剛從jquery開始。如何使用jQuery創建帶有幾張圖片的電影效果?

$(document).ready(function() { 

    // variable counter for image number. 
    slideNum = 1; 
    $("#startComic").click(function() { 
     var movie = []; 
     while (slideNum <= 11) { 
      movie[slideNum - 1] = '<img src="images/slide (' + slideNum + ').png"' + ' alt = "movie slide">'; 
      slideNum++; 
     } 
     for (var i = 0; i < movie.length; i++) { 
      $("#slide").html(movie[i]); 
      $("#slide").fadeIn(1000); 
      $("#slide").fadeOut(2000); 

     } 
    }); 
}); 

這裏是html。

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
\t <title>Web Comic</title> 
 
\t <meta charset="utf-8"> 
 
\t <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css"> 
 
\t <link rel="stylesheet" href="style.css"> 
 
\t <script src="../jquery-3.1.0.min.js"></script> 
 
\t <script src="script.js"></script> 
 
</head> 
 
<body> 
 
\t <button class="btn btn-primary" id="startComic">Start</button> 
 
\t <div id="slide"></div> 
 
\t <button class="btn btn-primary" id="playAgain">Play Again</button> 
 

 
</body> 
 
</html>

回答

1

這些淡入淡出和功能是異步的,它們同時運行這就是爲什麼你只看到最後一張圖像。

假定已經填充了數組,你可以試試:

function nextImage(intImage) { 
    // Bail after the last image. 
    // 
    if (intImage == movie.length) 
     return; 

    $("#slide").html(movie[intImage]); 
    $("#slide").fadeIn(1000); 
    $("#slide").fadeOut(1000); 

    // recursively call this function with increased intImage 
    // after a 2 second timeout to ensure both animations are complete 
    // 
    setTimeout(function() { 
     nextImage(intImage + 1); 
    }, 2000); 
} 

這樣的事情應該工作。填充您的陣列像以前那麼簡單地調用傳遞intImage爲0的功能,開始在圖像0:

$(document).ready(function() { 

    // variable counter for image number. 
    slideNum = 1; 
    $("#startComic").click(function() { 
     var movie = []; 
     while (slideNum <= 11) { 
      movie[slideNum - 1] = '<img src="images/slide (' + slideNum + ').png"' + ' alt = "movie slide">'; 
      slideNum++; 
     } 

     nextImage(0); 
    }); 
}); 

希望這有助於它打印了出來快,我在工作中目前是,削薄。

+0

非常感謝。它完全按照我的意願工作。代碼中存在拼寫錯誤:nextImage(intImage +!)。我無法將其更改爲1.請看看它。 – Br34th7aking

+0

格拉西亞斯指出,非常感謝和高興的幫助。 – Nunchy

相關問題