jQuery animate on an image replacement

2020-02-24 11:05发布

Hope you can advise I would like to add some simple fade in out of an image replacement which I have hooked into a select menu.ie,

$("#vehicle").change(function(){
    var selected = $(this).val();
    $("#selectedVehicle").attr('src', '/assets/images/mini/'+selected+'.png');
});

<img id="selectedVehicle" src="/assets/v2/images/select-vehicle.png">

any suggestions how I can do it?

3条回答
家丑人穷心不美
2楼-- · 2020-02-24 11:13

This will work best if you preload the images.

$("#vehicle").change(function(){
    var selected = $(this).val();
    var image = $("#selectedVehicle");
    image.fadeOut('fast', function () {
        image.attr('src', '/assets/images/mini/'+selected+'.png');
        image.fadeIn('fast');
    });
});

This will fade the image out, change the src, then fade it back in. Reference the jQuery docs for more information on the fading functions.

Again, you should preload your images, otherwise it might fade back while still loading.

查看更多
疯言疯语
3楼-- · 2020-02-24 11:22

I've gone for preloading the image on page load, rather than on the fly...:

$(document).ready(function () {
  function buildUrl(val) {
    return '/assets/images/mini/' + val + '.png';
  };

  $('#vehicle').change(function () {
    var value = $(this).val();

    $('#selectedVehicle').fadeOut('fast', function () {
      $(this).attr('src', buildUrl(value)).fadeIn('fast');
    });
  }).children('option').each(function () {
    var img = document.createElement("img");

    img.src = buildUrl($(this).val());
    img.onload = function () {};
  });
});
查看更多
可以哭但决不认输i
4楼-- · 2020-02-24 11:30

Example with "load" event:

$("#vehicle").on('change', function(){
  var selected = $(this).val();
  var image = $("#selectedVehicle");
  image.fadeOut('fast', function () {
     image.attr('src', '/assets/images/mini/'+selected+'.png');
  });
  image.one("load",function(){
    image.fadeIn('fast');
  });
});
查看更多
登录 后发表回答