2015-09-04 119 views
0

我有这个代码只在加载后才会在多个图像中淡入淡出。即使从缓存中加载图像,也会触发它。替换图像src,一旦加载图像

$(".image-class").one("load", function() { 
    $(this).fadeIn("slow"); 
}).each(function() { 
    if(this.complete) $(this).load(); 
}); 

现在,当加载完成时,如果图像的宽度小于130,我想在它的位置加载另一个图像。在加载第二张图像之前,不会显示任何内容。

$(imgID).one("load", function() { 
    // check if image is too small 
    if($(this).width() < 130){ 
     $(this).attr("src","larger_image.jpg"); 
    }else{ 
     $(this).fadeIn("slow"); 
    } 
}).each(function() { 
    if(this.complete) $(this).load(); 
}); 

这不加载不同的照片,如果宽度< 130.但它似乎永远不会触发load的第二图像。 fadeIn从不触发第二张图片,所以它从未显示过。

这怎么解决?

回答

3

因为使用.one()注册的处理程序,这将触发处理程序只有在此之后,处理被丢弃

var imgID = 'img'; 
 
$(imgID).on("load", function() { 
 
    // check if image is too small 
 
    if ($(this).width() < 130) { 
 
    $(this).attr("src", "//placehold.it/150x64"); 
 
    } else { 
 
    $(this).fadeIn("slow").off('load'); 
 
    } 
 
}).hide().each(function() { 
 
    if (this.complete) $(this).load(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<img src="//placehold.it/64x64" />

+0

一次http://jsfiddle.net/arunpjohny/hxpzjkwz/ –

+0

完美地工作。谢谢!将其中一个改为对代码有任何不利影响? – Yeti

+0

@Yeti我们正在删除处理程序,一旦它被使用...所以我想没有 –