A better implementation of a fading image swap with javascript / jQuery

前端 未结 3 1885
一个人的身影
一个人的身影 2021-01-20 07:26

This is less of a specific problem or error but more of a implementation question.

First of I\'d like to say that I\'ve been through a lot of fading image tutorials

3条回答
  •  执笔经年
    2021-01-20 07:54

    You can get the src attribute of an image and use .replace() to replace the url on hover!

    WORKING DEMO

    $('.fadein').each(function() {
    
        var std = $(this).attr("src");
        var hover = std.replace(".jpg", "_o.jpg"); 
        $(this).clone().insertAfter(this).attr('src', hover).removeClass('fadein').siblings().css({
            position:'absolute'
        });
        $(this).mouseenter(function() {
            $(this).stop().fadeTo(600, 0);
        }).mouseleave(function() {
            $(this).stop().fadeTo(600, 1);
        });
    });
    

    Or like:

    THIS

    $('.fadein').each(function() {  
        var std = $(this).attr("src");
        var hover = std.replace(".jpg", "_o.jpg");
        $(this).wrap('
    ').clone().insertAfter(this).attr('src', hover).removeClass('fadein').siblings().css({ position:'absolute' }); $(this).mouseenter(function() { $(this).stop().fadeTo(600, 0); }).mouseleave(function() { $(this).stop().fadeTo(600, 1); }); });

    What the script does:

    • var std = $(this).attr("src"); grab the SRC attribute
    • replace the imageRed.jpg with imageRed_o.jpg : var hover = std.replace(".jpg", "_o.jpg");
    • Than we had to wrap the first image into an element $(this).wrap('
      ')
    • so that now we can clone that image and give it a different src and place it UNDERNEATH the first one .clone().insertAfter(this).attr('src', hover)
    • and we have to remove from the second image the class '.fadein' (only the first image will have that class!) .removeClass('fadein')
    • after we cloned that image we set the image one OVER the second by assigning it a css position absolute: .siblings().css({position:'absolute'});
    • Than on mouse enter/leave we can just play with the visibility of the first image.

提交回复
热议问题