将淡入淡出添加到jQuery图像交换

时间:2014-06-17 11:22:54

标签: 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'); // 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;
});

由于

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

$('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;
});

A simple fiddle demo.

答案 1 :(得分:1)

将其分解为步骤:

  1. 淡出图像
  2. 等待淡出完成
  3. 更改src
  4. 等待图片加载
  5. 淡入
  6. 演示:http://jsfiddle.net/abhitalks/EqEma/

    您可以使用与使用相同的处理程序执行步骤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:http://jsfiddle.net/abhitalks/EqEma/1/

    $('a.swatchItem').click(function() { 
        $("#carItem").fadeOut();
        $("#carItem").attr('src', "...");   
        return false;
    });