2010-09-30 66 views
0

有一個畫廊,一邊有縮略圖的大圖像。點擊縮略圖,大圖像淡出,新的圖像淡入(src從鏈接的rel屬性中調用)。JQuery淡入/淡出圖片點擊跳轉,同時加載新圖片

問題:舊圖像淡出,重新出現,然後跳轉到新圖像...我猜新圖像還沒有加載,因爲它只發生在第一次圖像加載。


HTML

<div id="image"><img src="http://marilynmcaleer.com/images/BeachRoad-title.jpg" width="480" height="383" /></div> 
<div id="thumbnails"> 
    <div class="thumbnail-homes"><a href="#" rel="http://marilynmcaleer.com/images/BeachRoad-title.jpg" class="image"><img src="http://marilynmcaleer.com/thumbnails/homeportrait_thumbs/BeachHouse_thumb.jpg" width="136" height="90" alt="Beach House" /></a></div> 
    <div class="thumbnail-nudes"><a href="#" rel="http://marilynmcaleer.com/images/ReducedFigure-title.jpg" class="image"><img src="http://marilynmcaleer.com/thumbnails/nude thumbs/reducedfigure_thumb.jpg" width="136" height="90" alt="Patience" /></a></div> 

    <div class="thumbnail-murals"><a href="#" rel="http://marilynmcaleer.com/images/BabyElephant-title.jpg" class="image"><img src="http://marilynmcaleer.com/thumbnails/mural thumbs/babyelephant_thumb.jpg" width="136" height="90" alt="Baby Elephant" /></a></div> 
    <div class="thumbnail-paintings"><a href="#" rel="http://marilynmcaleer.com/images/Charlevox-title.jpg" class="image"><img src="http://marilynmcaleer.com/thumbnails/homeportrait_thumbs/Charlevouix_thumb.jpg" width="136" height="90" alt="Boat Shed" /></a></div> 
</div> 
<div class="clear"></div> 

JQuery的

$(function() { 
     $(".image").click(function() {     // something with class "image" gets clicked and a function happens 
      var image = $(this).attr("rel");    // variable (image) is defined to be the rel attribute of the link that was clicked 
      $('#image img').hide();        // hides the old big image 
      $('#image img').attr('src', image); 
      $('#image img').fadeIn();      // animate to fade in 
     return false; 
    }); 
}); 

直播網站:http://marilynmcaleer.com/


任何想法如何解決這一問題?

回答

3

使用load事件,這樣一旦加載圖像褪色開始,像這樣:

$(function() { 
    $(".image").click(function() { 
    var image = $(this).attr("rel"); 
    $('#image img').hide().one('load', function() { 
     $(this).fadeIn(); 
    }).attr('src', image); 
    return false; 
    }); 
}); 

這種結合使用.one(),以不附加多個事件處理程序(將每次一個)load處理程序,將在圖像加載後淡入...確保在綁定load處理程序後設置src,以便它連接並準備就緒。即使圖像是從緩存中提取的,這也是可行的。


另外,好一點的解決方案,如果可能的就是該處理程序綁定只有一次,就像這樣:

$(function() { 
    $('#image img').load(function() { 
    $(this).fadeIn(); 
    }); 
    $(".image").click(function() { 
    var image = $(this).attr("rel"); 
    $('#image img').stop().hide().attr('src', image); 
    return false; 
    }); 
}); 

然後每次加載時,它會再次淡入的.stop()是處理連續的多次點擊,排隊動畫。

+0

你真棒。謝謝! – christina 2010-09-30 16:38:01

0

我總是有嵌套元素不返回正確的事件目標的問題,所以你可能需要使用現場活動:

$(function() { 
     var img = $('#image img'); 
     img.load(function(e) { 
      img.fadeIn(); 
     }); 
     $(".thumbnails").live('click', function(e) { 
      var rel = $(e.target).closest("a").attr("rel"); 
      img.stop().hide().attr('src', rel); 
     }); 
    });