2010-09-30 45 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); 
     }); 
    });