簡體   English   中英

我想以“波浪”形式加載圖像。

[英]I would like to load images in a “wave”..

<html>
<section>

<style>
img{
 width: 150px;
 height:150px;
 float:left;
 }
 </style>
 </section>


 <script>

 var img = undefined,
 section = document.querySelector('section'),
 images=[
 "http://www.psdgraphics.com/file/red-number-0.jpg",
 "http://www.psdgraphics.com/file/red-number-1.jpg",
 "http://www.psdgraphics.com/file/red-number-2.jpg",
 "http://www.psdgraphics.com/file/red-number-3.jpg",
 "http://www.psdgraphics.com/file/red-number-4.jpg",
 "http://www.psdgraphics.com/file/red-number-5.jpg",
 "http://www.psdgraphics.com/file/red-number-6.jpg"
  ];

  function loadImage( i ){
   img = document.createElement('img');
   section.appendChild(img);
   img.dataset['index'] = i;
   img.src=images[i];
 }
 for(var i=0;i<images.length;i++){

  loadImage(i)

  }

  </script>


  </html>

這是我的代碼,目前我同時接收所有圖像...僅在加載前一個圖像時才想加載每個圖像。

任何幫助將不勝感激

只需將偽遞歸回調分配給onload處理程序即可:

function loadImage( i ){
  if(i >= images.length) return;
  var img = document.createElement('img');
  section.appendChild(img);
  img.dataset['index'] = i;
  img.src=images[i];
  img.onload = () => loadImage(i+1);
}

loadImage(0);

或使用一些新的ES 7內容:

(async function(){

 for(var i = 0; i < images.length; i++){
  var img = document.createElement('img');
  section.appendChild(img);
  img.dataset['index'] = i;
  img.src=images[i];

  await new Promise(r => image.onload = r );
 }

 })()

可能一些setTimeout以及遞歸可以帶來很好的效果:

 var img = undefined, section = document.querySelector('section'), images = [ "http://www.psdgraphics.com/file/red-number-0.jpg", "http://www.psdgraphics.com/file/red-number-1.jpg", "http://www.psdgraphics.com/file/red-number-2.jpg", "http://www.psdgraphics.com/file/red-number-3.jpg", "http://www.psdgraphics.com/file/red-number-4.jpg", "http://www.psdgraphics.com/file/red-number-5.jpg", "http://www.psdgraphics.com/file/red-number-6.jpg" ]; function loadImage(i) { img = document.createElement('img'); section.appendChild(img); img.dataset['index'] = i; img.src = images[i]; } var index = 0; function loadNext() { if(index < images.length) { loadImage(index); setTimeout(function(idx){ loadNext(); },200, index++); } } loadNext(); 
 img { width: 150px; height: 150px; float: left; } 
 <html> <section> </section> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM