Fade in and out with jQuery Image Gallery

2019-08-30 18:58发布

问题:

I've made this simple jQuery image gallery http://jsfiddle.net/RVermeulen/XNsHC/3/

But I can't make a nice fadeOut and In in it, because if I do this (with fadeOut and In in it):

$(document).ready(function() {

    $(".small_image").click(function() {
        event.preventDefault();
        var image = $(this).attr("rel");
        $('#current_image').fadeOut(300);
        $('#current_image').html('<img width="370" src="' + image + '"/>');
        $('#current_image').fadeIn(300);
    });

});

It looks like the .html function loads faster than the FadeIn, so it's no "smooth" fade. Does anyone know how to fix this with a delay or something?

回答1:

You need to use the complete callback to change the image after the image is faded out:

$(".small_image").click(function () {
    event.preventDefault();
    var image = $(this).attr("rel");
    $('#current_image').fadeOut(300, function() {
        $('#current_image').html('<img width="370" src="' + image + '"/>');
        $('#current_image').fadeIn(300);
    });
});

jsFiddle example



回答2:

Is this what you were looking for?

FIDDLE

$(document).ready(function () {
    $(".small_image").click(function () {
        event.preventDefault();
        var image = $(this).prop("rel");
        $('#under').prop('src', image);
        $('#above').fadeOut(600, function () {
            $('#above').prop('src', $('#under').prop('src')).css('display', 'block');
        });
    });
});