jQuery 动画图像替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2744579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:11:42  来源:igfitidea点击:

jQuery animate on an image replacement

jqueryimageanimation

提问by Lee

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,

希望您能建议我想添加一些简单的淡入淡出图像替换,我已将其连接到选择 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?

有什么建议我该怎么做?

回答by Matt

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 docsfor more information on the fading functions.

这将使图像淡出,更改src,然后将其淡入。有关淡入淡出功能的更多信息,请参阅jQuery 文档

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

同样,您应该预先加载您的图像,否则它可能会在加载时淡出。

回答by Matt

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

回答by Arthur Shlain

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