Hide images until they're loaded

两盒软妹~` 提交于 2019-12-18 05:24:12

问题


I got a jQuery script which is dinamically appending data to the "holder" at some timeinterval. The data looks like this:

<div class="item-box etc etc"> <img src="data.png"> </div>

and I'm loading like 50 images at once, my goal is to make them fadeIn, when each image is loaded.

I've tried the following:

parentDiv.on("load", "img", function() {
    $(this).parent().fadeIn(500);
});

Fiddle: http://jsfiddle.net/3ESUm/2/

but seems that on method doesn't have load or ready methods. I ran out of ideas.


回答1:


just set the onload property when you add the image.

var img = new Image();
img.src = "some url"
img.onload=function(){$(img).fadeIn(500);}
document.getElementByID('parent').appendChild(img);

see working example here




回答2:


You can add your images in first-loaded-first displayed order like this:

Demo: http://jsfiddle.net/m1erickson/7w6cb/

var imageURLs=[];
var imgs=[];
imageURLs.push("house100x100.png");
imageURLs.push("house32x32.png");
imageURLs.push("house16x16.png");

for(var i=0;i<imageURLs.length;i++){

    imgs.push(document.createElement("img"));
    imgs[i].onload=function(){
        var id=this.myId;
        this.id=id;           
        document.body.appendChild(this);
        $("#"+id).hide().fadeIn(1500);
    }
    imgs[i].myId=i;
    imgs[i].src=imageURLs[i];
}


来源:https://stackoverflow.com/questions/21736566/hide-images-until-theyre-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!