【问题标题】:Getting to grips with pre-loading images掌握预加载图像
【发布时间】:2014-10-04 15:55:06
【问题描述】:

我在使用 JS 预加载图像时遇到了一些问题。我有一个小提琴,我试图创建三个图像对象并一个一个加载它们,但是我只得到一个图像?任何帮助表示赞赏。

http://jsfiddle.net/gq1oqnxb/1/

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

        var images = new Array();

    images[0] = 'http://hdcomputerwallpaper.com/wp-content/uploads/2013/12/Puppy-images.jpg';
    images[1] = 'http://hdcomputerwallpaper.com/wp-content/uploads/2013/12/Puppy-images.jpg';
    images[2] = 'http://wallfc.com/wp-content/uploads/2014/09/Little-Birds.jpg';
    var i = 0;      

    while(i < images.length){

    var image = new Image(50,50);
    image.src = images[i];
    image.onload = function(){

                        $('body').append(image);
                        i++;
                                }
    i++
    }



    });

</script>
</head>

<body>

</body>

【问题讨论】:

    标签: javascript jquery preloading


    【解决方案1】:

    Fiddle Demo

    imageLoader(0); //call the function with first image to load `0` as index starts from `0`
    function imageLoader(i) { //function to load images one by one and pass the array index
        var image = new Image(50, 50); //create a new image
        image.src = images[i]; //set src of the image from images array
        image.onload = function () { //on image load 
            $('body').append(image); //append to the the body
            if (++i >= images.length) return; //increment i check the length of images is exceeded than return
            imageLoader(i); //more images are present in array then call the function again 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-09
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-27
      • 2022-01-26
      相关资源
      最近更新 更多