Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

javascript - Show loading gif while image is loading

I made some code where the user can upload some images from a zip. On the next page I need to show all the images seperatly in a 85*85 px frame.

The problem is that it may take some time for all the images to load. So I want to show a loading gif while the user waits for the image to load.

I've set the src of the images to be the loading gifs, while I created some checkboxes with the real source as id

echo "<td><img src="beelden/ajax-loader-black-16.png" id="img".$image."" style=" width: 85px; height: 85px; border: 1px solid gray; background-color: #fff; padding: 10px;">";
echo "<input type="checkbox" id="img[".$image."]" name="check_image[]" value="".$filename."" /></td>";
<input type="hidden" name="aantal" id="aantal" value="<?=$image?>" >

Then I created some javascript to check if the image is loaded, and when it is, it is supposed to replace the source of the image.

<script>
    var aantal = document.getElementById("aantal").value;
    for(var i = 0; i < aantal; i++){
        var source = document.getElementById("img["+i+"]").value;
        var img = new Image();
        img.onload = function(){
            $("#img"+i).attr('src', source);
        }();
        img.src = source;
    }
</script>

But this does not work the way I expected, I think it fires for all of the images as soon as the first one is loaded. Any ideas what I am doing wrong or how to fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can set the background of an image to the loading gif. It is a simple css trick. You wouldn't need then to make a js script.

.loading {
  background: transparent url('http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif') center no-repeat;
}
<img class="loading" src="http://placehold.it/106&text=1" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=2" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=3" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=4" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=5" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=6" width="106px" height="106px" />
<img class="loading" src="http://placehold.it/106&text=7" width="106px" height="106px" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...