繁体   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