2012-03-06 74 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; 
}