2012-03-06 131 views
0

我正在寻找正确的方法来做到以下几点:jQuery的隐藏图像,变更内容,显示图像

$("#some-image").fadeOut(); 
$("#some-image").attr("src", "new-src.png"); 
$("#some-image").fadeIn(); 

定时目的,下面套起来更近,但我知道这仍是不正确的:

$("#some-image").fadeOut(function(){ 
    $(this).attr("src", "new-src.png").fadeIn(); 
}); 

什么是正确的方式做以下,依次是:

  1. 淡出图像输出
  2. 图片后已消退,加载一个新的src
  3. 后的新形象已经完全加载,褪色图像回

干杯!

回答

0

你的问题可能是新的图像不加载,直到包含它已经褪色的DOM元素后,确保图像充分调用淡入()之前加载:

$("#some-image").fadeOut(function(){ 
    var tgt = $(this), 
     img = new Image, 
     src = "new-src.png"; 
    img.onload = function() { 
     tgt.attr('src', src).fadeIn(); 
    }; 
    img.src = src; 
}); 

更妙的是,提前加载图像的时间:

<script> 
    // Outside of $(function() {}) 
    function preload_img(src) { 
     var img = new Image; 
     img.src = src; // loads immediately, maybe even before DOMReady 
    } 
</script> 

然后,你将不必担心是否当用户触发您的淡入/出的图像已经被加载。

0

使用回调函数。一旦fadeOut完成,我们更改src并在src更改后淡入图像。

$("#some-image").fadeOut(function(){ 
    //after the fadeout completes, change the src of the image. 
    $(this).attr("src", "new-src.png").fadeIn();  
});