2015-09-04 120 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我們正在刪除處理程序,一旦它被使用...所以我想沒有 –