简体   繁体   中英

Jquery: FadeIn on image src swap

I have a piece of JQuery script that changes the src of an image on click:

var imgsrc;
$('#thumbs img').click(function(){
imgsrc = $(this).attr('src');
$('#mainphoto img').attr('src', imgsrc);

I am wondering if theres a way to add .fadeIn() to this at all?

I have tried:

$('#mainphoto img').fadeIn().attr('src', imgsrc);

But this does not work.

Can anyone suggest a way to adjust the symantecs to accomodate this?

Try

$('#thumbs img').click(function(){
    var imgsrc = $(this).attr('src');
    $('#mainphoto img').fadeOut(function(){
       $(this).attr('src', imgsrc).fadeIn();
    });
});

Try this

$('#thumbs img').click(function() {
    var imgsrc = $(this).attr('src');

    $('#mainphoto img').fadeOut().attr('src', imgsrc).load(function() {
        $(this).fadeIn();
    });
});

I have done an example in jsFiddle for you.

Basically, what I do is to listen the click event over the image. When the click is performed, I change the display of the current image to none, also change the src of the image to the new one and then do the fadeIn (which restores the display).

The Javascript code is:

$('#image').click(function(){
        $(this).css("display", "none");
        $('#image').attr('src', 'http://www.stat4you.com/theme/0.1.11/images/stat4you.png');
        $("#image").fadeIn("slow");
    })​

In the jQuery documentation page of fadeIn ( here ) there are some other similar examples:

$('#thumbs img').click(function () {
 var imgsrc = $(this).attr('src');
            $('#mainphoto img').fadeOut(function () {
                $(this).attr('src', imgsrc);
                $(this).fadeIn();
            });
        })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM