1

A jQuery related question - I have a little gallery style script working - a list of thumbnails and associated larger images switching on thumbnail click, like so:

$('#thumbs').delegate('img','click', function(){
    $('#largeImage').attr('src',$(this).attr('src').replace('thumb','large'));
});

My question is: what's the easiest way of making the image transitions fade between one another rather than a straight switch?

Many thanks in advance for your help.

4

3 回答 3

2

You can fadeOut the image, then fadeIn in the callback after swapping the src:

$('#thumbs').delegate('img','click', function(){
    var src = this.src.replace('thumb', 'large');
    $("#largeImage").fadeOut(function() {
        this.src = src;
        $(this).fadeIn();
    });
});

Live example using our gravatars | source

(Note that there's no need to go through attr for src; it's reflected on the DOM element.)

于 2012-05-14T09:06:23.480 回答
1

The easiest way would be to use one of the jQuery cycle plugins that exist. The one @ malsup.com is a popular choice.

If you want to code it yourself, you'll have to use 2 image elements and position one behind the other, and fade out the one on top.

You can do this by using a position: relative on the parent of the <img /> and a position: absolute; top: 0; left: 0; on the <img />. After you've faded the top image out fadeOut(), you can remove it in the callback:

$('img_on_top').fadeOut('slow', function () {
    $(this).remove();
});
于 2012-05-14T09:06:17.240 回答
0
$('#thumbs').delegate('img','click', function(){
    var src = $(this).attr('src').replace('thumb','large');
    $('#largeImage').fadeOut(100,function() {
      $(this).attr('src',src).fadeIn();
    });
});
于 2012-05-14T09:06:37.027 回答