获取加载图像淡出并使实际图像淡入

时间:2015-01-15 05:01:03

标签: javascript jquery

我正在使用下面的代码在加载实际图像之前显示加载图像。如果加载实际图像,如何让加载图像淡出并使实际图像平滑淡入? setTimeout()用于演示目的。

小提琴:http://jsfiddle.net/95rpu029/11/

HTML

<article class="project">
    <img width="375" height="375" src="http://i.imgur.com/lJpvTU3.gif" class="attachment-home-thumb" data-mainSrc="http://dummyimage.com/375x375/000/fff">
    <img width="375" height="375" src="http://i.imgur.com/lJpvTU3.gif" class="attachment-home-thumb" data-mainSrc="http://dummyimage.com/375x375/f00/fff">
    <img width="375" height="375" src="http://i.imgur.com/lJpvTU3.gif" class="attachment-home-thumb" data-mainSrc="http://dummyimage.com/375x375/0f0/fff">
</article>

JS

$(function () {
    setTimeout(function () {
        var imgs = $("article.project img.attachment-home-thumb");
        $.each(imgs, function () {
            var $this = $(this);
            var im = new Image();
            im.onload = function () {
                var theImage = $this;
                theImage[0].src = im.src;
                $this.show('fast');
            };
            im.src = $this.data("mainsrc");
        });
    }, 500);
});

CSS

article.project {
    display: block;
    float: left;
    margin: 0 1% 2%;
    max-width: 375px;
    overflow: hidden;
    position: relative;
    width: 23%;
}
article.project img {
    display: inline-block;float:left;
    margin: 10;
    padding: 10;
    max-width: 100%;
    height: auto;
}

1 个答案:

答案 0 :(得分:1)

请参阅http://jsfiddle.net/95rpu029/12/

您可以淡化图像,更改其来源,然后将其淡入淡出:

 im.onload = function () {
     var theImage = $this;
     theImage.fadeOut("fast", function(){
         theImage[0].src = im.src;
         theImage.fadeIn("fast");
     });
 };