向jQuery图像交换添加淡入淡出

向jQuery图像交换添加淡入淡出,jquery,image,fadein,fade,Jquery,Image,Fadein,Fade,我正在开发一个应用程序,当单击色样时,可以显示不同颜色的汽车。我已经构建了jQuery,以便根据单击的样例很好地交换图像 然而,我正在努力使新图像在已经可见的图像上很好地淡入 $('a.swatchItem').click(function() { // on click of swatch var carID = $(this).attr('id'); // grab the clicked ID $('a.swatchItem').removeClass('active');

我正在开发一个应用程序,当单击色样时,可以显示不同颜色的汽车。我已经构建了jQuery,以便根据单击的样例很好地交换图像

然而,我正在努力使新图像在已经可见的图像上很好地淡入

$('a.swatchItem').click(function() { // on click of swatch
    var carID = $(this).attr('id'); // grab the clicked ID
    $('a.swatchItem').removeClass('active'); // Remove active class
    $(this).addClass('active'); // Add active class to current swatch
    $("#carItem").attr('src',"img/models/longtitude/" + carID + ".png"); // replace with new car image
    return false;
});
谢谢

您可以尝试以下方法:

$('a.swatchItem').click(function() { // on click of swatch
  var carID = $(this).attr('id'); // grab the clicked ID
  $('a.swatchItem').removeClass('active'); // Remove active class
  $(this).addClass('active'); // Add active class to current swatch
  $("#carItem").fadeOut('fast', function(){
      $(this).attr("src", "img/models/longtitude/" + carID + ".png").fadeIn();
  }); // replace with new car image
  return false;
});
把它分成几个步骤:

  • 淡出图像
  • 等待淡出完成
  • 更改
    src
  • 等待图像加载
  • 淡入
  • 演示:

    您可以使用与使用相同的处理程序执行步骤1到3:

    $('a.swatchItem').click(function() { 
        // fade the image out
        $("#carItem").fadeOut(function() {
            // on completion change the src
            $("#carItem").attr('src', "...");     
        });
        return false;
    });
    
    对于步骤4和5,将处理程序添加到映像本身:

    $("#carItem").load(function() {
        // once the image is loaded, fade it back in
        $(this).fadeIn()
    });
    
    编辑:

    事实上,您可能不会等待淡出完成。可以跳过步骤2。图像可以与淡出动画一起加载

    演示2:


    我将把这个标记为正确,因为你已经回答了我的问题。(非常轻微的)问题是它会淡出然后进入(因此你可以简单地看到背景)。我的意思是,但没有正确解释,我希望新图像在顶部淡出,这样就可以在看不到任何背景的情况下平滑过渡。我可能会使用你的例子,并在某种程度上使用一些z-index:)这确实有效-但我仍然会在新图像加载后逐渐消失(可能是Chrome Mac的问题)。
    $('a.swatchItem').click(function() { 
        $("#carItem").fadeOut();
        $("#carItem").attr('src', "...");   
        return false;
    });