2016-07-28 113 views
1

我一直在嘗試通過更改圖像元素的值,使用循環遍歷每個圖像,然後返回到原始圖像來創建html圖像滑塊。Javascript滑塊循環

但是一旦到達循環結束,它不會繼續。

這裏是我的js代碼:

window.onload = function() { 
 
    var x = 0 
 
    while(x<1000){ 
 
    setTimeout(function() { 
 
     document.getElementById('carousel').src='img/header2.jpg'; 
 
     setTimeout(function() { 
 
     document.getElementById('carousel').src='img/header3.jpg'; 
 
     setTimeout(function() { 
 
      document.getElementById('carousel').src='img/header.jpg'; 
 
      }, 5000); 
 
     }, 5000); 
 
     }, 5000); 
 
    x = x+1 
 
    } 
 
}

+0

您在x增量行上缺少分號。 – TheValyreanGroup

+1

這不是必需的。 – RamenChef

+0

我之前做了類似的事情。也許我的小提琴會給你一些指導:https://jsfiddle.net/Currell/wb0o99cq/ – Scott

回答

0

我建議你不要做while循環在這種情況下。執行時只需調用setTimeout

window.onload = function() { 
    /* Element */ 
    var carousel = document.getElementById('carousel'), 
    /* Carousel current image */ 
    cimage = 2, 
    /* Carousel source images */ 
    csources = [ 
     'img/header2.jpg', 
     'img/header3.jpg', 
     'img/header.jpg' 
    ]; 

    function changeCarouselImage() { 
     // Reset the current image if it's ultrapassing the length - 1 
     if(cimage >= 3) cimage = 0; 
     // Change the source image 
     carousel.src = csources[cimage ++]; 
     // Re-call the function after 5s 
     setTimeout(changeCarouselImage, 5000); 
    } 

    setTimeout(changeCarouselImage, 5000); 
}; 
0

最終函數不會設置另一個超時,因此動畫不會繼續。分解成單獨的函數應該有所幫助:

var carousel = document.getElementById('carousel'); 

function ani1() { 
    carousel.src = 'img/header.jpg'; 
    window.setTimeout(ani2, 500); 
} 

function ani2() { 
    carousel.src = 'img/header2.jpg'; 
    window.setTimeout(ani3, 500); 
} 

function ani3() { 
    carousel.src = 'img/header3.jpg'; 
    window.setTimeout(ani1, 500); 
} 

window.onload = ani1; 
+0

謝謝這個作品,但是不會再次通過圖像重複?對不起,我是JavaScript新手。 –