2012-12-06 48 views
0

我目前使用以下方法來淡化我的網站上的圖像:jQuery的淡入淡出和simulaneously

$(document).ready(function() { 
    $('ul.image-switch li').mouseover(function(e) { 
    if (e.target.nodeName.toLowerCase() == 'a') return; 

    var image_src = $('a', this).data('image'); 
    var img = $('.image-container img'); 

    if (img.attr('src') != image_src) { // only do the fade if other image is selected 
     img.fadeOut(200, function() { // fadeout current image 
      img.attr('src', image_src).fadeIn(200); // load and fadein new image 
     }); 

    } 
}); 
});​ 

在這一行動的一個例子是http://www.sehkelly.com/#news

正如你可以看到,當前的圖像必須淡出的新的前消失。

我想,動作要simulaneous。請 - 有誰知道我可以做到這一點?

非常感謝。

編輯:無知的新手。代碼示例非常感謝。

回答

2

創建一個新的img元素頂部的實際之一,然後淡入這個新的形象。你需要一些CSS來將新圖像放在舊圖像的頂部。

絕對不能只用一個img元素來做到這一點。

if (img.attr('src') != image_src) { // only do the fade if other image is selected 
    img.after(
     $('<img />').attr('src', image_src).fadeIn(200) 
    ); 
    img.fadeOut(200); 

} 

您也想在開始淡入淡出之前等待新圖像加載。 (檢查正確的功能jQuery文檔,並淡化負載回調中的圖像)。

+0

非常感謝。你知道我在哪裏可以找到示例代碼嗎? –

+0

用一個快速示例編輯的答案:) – Ulflander

0

這裏的Ulflander的想法的實現,因爲發佈的代碼是不完整http://jsfiddle.net/8nBqD/1/

訣竅是絕對定位在一個頂部的第二圖像你淡出

HTML

<img id='pic1' src="http://periodictable.com/Samples/009.3b/s7.JPG" /> 
<img id='pic2' src="http://icons.iconarchive.com/icons/vargas21/aquave-metal/256/Sample-icon.png" /> 

CSS

#pic2 { 
    position: absolute; 
    display: none; 
}​ 

JS

// Fade out the image, and replace it with the new one after the fade is over 
$("#pic1").fadeOut(500, function() { // fadeout current image 
    this.src = 'http://icons.iconarchive.com/icons/vargas21/aquave-metal/256/Sample-icon.png';   
    $(this).show(); 
}); 

// Fade in the new image placing it on top of the original one 
$("#pic2").offset($("#pic1").offset()).fadeIn(500, function(){ 
    // Hide it since we are showing the original image with the new src   
    $(this).hide(); 
}); 

我們甚至可以寫一個插件,使這個容易複用

(function($) { 
    $.fn.imageFader = function(newSrc, seconds) { 
     $(this).each(function() { 
      var $img = $(this); 
      $img.fadeOut(seconds, function() { 
       this.src = newSrc; 
       $img.show(); 
      }); 
      var $tempImg = $('<img src="'+newSrc+'" style="position:absolute;display:none;" />').appendTo('body'); 
      $tempImg.offset($img.offset()).fadeIn(seconds, function(){ 
       $tempImg.remove(); 
      }); 
     }); 
    }; 
})(jQuery); 

而且使用它像http://jsfiddle.net/8nBqD/5/

$('img').imageFader('picture.png', 1000);