我想在" wave"中加载图片。

时间:2017-08-16 17:24:39

标签: javascript arrays

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

这是我的代码,目前我同时收到所有图片... 我想只在前一个图像加载时加载每个图像..

任何帮助都将是感激之情

2 个答案:

答案 0 :(得分:1)

只需为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 );
 }

 })()

答案 1 :(得分:0)

可能一些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>

相关问题