2012-03-06 71 views
1

顯示「加載」,而新的圖像加載

<img src="..." class="myImage"> 
<a href="..." class="changeImage"> 

$(function(){ 
    $('a.changeImage').click(function(){ 
     $('img.myImage').attr('src',NEWVALUE); 
    }); 
}); 

當我點擊鏈接,我注入了新的src到.myImage。在新的src加載時可能會顯示加載圖片嗎?

回答

1

可以使用load event(未測試的代碼)

<img src="smallLoader.png" alt="loading" id="loading" /> 
<img alt="bigImage" id="bigImage" style="display:none" /> 

<script type="text/javascript"> 
$(document).ready(function() { 

    $('#bigImage').load(function() { 
     $('#loading').hide(); 
     $('#bigImage').show(); 
    }); 

    $('#bigImage').attr("src", "bigimage.png"); 
}); 
</script> 
+0

jusdt不要忘了,包括裏面的一切$(文件)。就緒 – dynamic 2012-03-06 11:15:58

+0

我編輯的代碼。雖然列出的代碼本身並不需要,但在這種情況下,$(document).ready是一個適當的措施,尤其是在將腳本移動到其他位置時。 – Candide 2012-03-06 11:37:56

+1

您需要在更改'src'屬性之前添加'load'處理程序以使其可靠地工作。 – 2012-03-06 11:48:58

1

看看jquery.blockui插件。它可能適合你的需要。

3
$(function(){ 
    $('a.changeImage').click(function(e){ 
     e.preventDefault(); 
     //show the loading div 
     $('img.myImage').attr('src',NEWVALUE); 
     $("img").trigger("onload"); 
    }); 

$("img").bind("onload",function(){ 

//remove the loading div 
}); 
}); 

http://jsfiddle.net/PrXSW/9/

+0

完全同意,但沒有明確的觸發撥弄它沒有觸發 – 2012-03-06 11:17:54

4

是的,你應該使用圖像預壓

var newImage = new Image(); 
var loadingSrc = 'loading.gif'; 
$('img.myImage').attr('src', loadingSrc); 
newImage.onload = function() { 
    $('img.myImage').attr('src', newImage.src); 
}; 
newImage.src = NEWVALUE; 
0

最簡單的解決辦法是將申報通過CSS加載img爲background-image

#loaded-image { 
    /* shows loading icon until picture is fully loaded */ 
    background-image: url(loading.gif); 
    background-repeat: no-repeat; 
}