2013-02-26 64 views
0

我有一組「圖像」,每個圖像具有不同的Z-index。頂部的「卡片」會連續下到Z-index最低的卡片(我們稱之爲「image1」),直到「image1」出現在其他頂部。這是一個動畫,但我無法讓for循環迭代一段時間。我想在1秒內嘗試30張圖片。下面是代碼:JavaScript - 用於堆疊圖像的循環迭代延遲


function placeImage(x) { 
    var div = document.getElementById("div_picture_right"); 
    div.innerHTML = ""; // clear images 

    for (counter=1;counter<=x;counter++) { 
     var image=document.createElement("img"); 
     image.src="borboleta/Borboleta"+counter+".png"; 
     image.width="195"; 
     image.height="390"; 
     image.alt="borboleta"+counter; 
     image.id="imagem"+counter; 
     image.style.backgroundColor="rgb(255,255,255)" 
     image.style.position="absolute"; 
     image.style.zIndex=counter; 
     div.appendChild(image); 
    } 
}; 

var animaRight = function(x) { 
     var imageArray = []; 
     for (counter=1;counter<=x;counter++) { 
      imageArray[counter-1] = document.getElementById("imagem"+counter); 
     } 
    function delayLoop(x) { 
     for (counter=imageArray.length;counter>1;counter--) { 
      if (imageArray[counter-1].style.zIndex==counter) { 
       imageArray[counter-1].style.zIndex-=counter; 
       setTimeout("delayLoop()", 1000/x); 
      }   
     } 
    } 
    delayLoop(x); 
}; 

任何幫助我非常感謝!我嘗試了一些setTimeout的功能,但我恐怕我做錯了(安置,也許?)。如果你需要,我會用我試過的代碼編輯代碼。

+0

沒有你所嘗試的,很難猜測你的問題,但也許這(有關問題)(http://stackoverflow.com/questions/14791158/javascript-settimeout-and-loops)將幫助? – 2013-02-26 14:31:01

+0

我馬上編輯!問題是,我嘗試了很多方法,所以我必須選擇一個。 – 2013-02-26 14:32:12

回答

0

這就是你想要的嗎?

var animaRight = function(x) { 
    var imageArray = []; 
    for (counter=1;counter<=x;counter++) { 
     imageArray.push(document.getElementById("imagem"+counter)); 
    } 
    for (var i=0; i<x; i++) { 
     (function(i) { 
      setTimeout(function(){ 
       imageArray[i%imageArray.length].style.zIndex=i*-1 
      }, i*1000); 
     })(i); 
    } 
}; 

如果它做到了你想要的,我會更多地解釋它。

+0

不幸的是,它不起作用。之前,我可以改變每張圖片的Z-index。有了這段代碼,它不會改變我想要的。儘管我會用你的推理來適應我的所見,並看看它是否有效。順便說一下,有一些推薦的閱讀材料可以幫助我們改進嗎?我從閱讀和分析代碼開始,使用w3schools寫我自己。這是我的第一個項目,但我發現的書不涉及這個主題。 – 2013-02-26 14:58:03

+0

它的工作!謝謝!我意識到我做錯了! – 2013-02-26 19:04:42