奇怪的JQuery图像fadein / fadeout行为

时间:2014-06-26 09:58:55

标签: jquery image fadein fadeout swap

我有这个HTML:

<div class='rightTile' >
    <img class='bigFace' src='content/images/teamSlide/zdjecie-Basia.png'>
</div>

我使用这个jQuery代码淡出/淡化图像:

$('.someElement').on('click', function(){
    $('.bigFace').fadeOut('fast', function(){
        $('.bigFace').attr('src', anotherPicPath).fadeIn();
    }); 
});

我有很多带有'someElement'类的元素,而在data-src属性中它们有不同的图像源。 问题是,当我第一次点击具有类someElement:

的特定元素时
  1. 当前bigFace图片fadesOut
  2. 比fadesIn(使用相同的来源)
  3. 而不是图片更改为具有新src的文件
  4. 当我再次点击同一个元素时,例如它是第二次完美运作:

    1. 当前bigFace图片fadesOut,
    2. 而不是img with swapped source fadesIn。
    3. 我认为它可能与图像预加载相关,所以我用CSS预加载它们,但它没有给我任何东西。 作为一个有力的测试方法,我甚至触发了点击每个.someElement元素,但它仍然没有产生任何效果。

      只有当我将代码上传到外部服务器时才会发生(生产可以说)。在localhost上 - 一切都很好。

      我不知道为什么。请帮忙:) 问候!

2 个答案:

答案 0 :(得分:0)

浏览器需要加载图像数据,一旦显示就会发生。要预先加载图像,您必须在显示之前对其进行初始化:

$('.someElement').on('click', function(){
    var image= new Image();
    $(image).load(function () {
        $('.bigFace').fadeOut('fast', function(){
        $('.bigFace').attr('src', image.src).fadeIn();
    }); 
    image.src = anotherPicPath;
});
这样,首先加载图像然后交换。请注意,在点击和图像交换之间可能会有几秒钟......

你的小提琴:http://jsfiddle.net/e5st4/18/

答案 1 :(得分:0)

你可以查看这个问题:smooth-image-fade-out-change-src-and-fade-in-with-jquery,它可以帮助你检查图像的加载时间,然后淡入新图像,如下面的代码:

$('.click').click(function() {
   $('img.class').fadeOut(300, function(){
      $(this).attr('src','new_src.png').bind('onreadystatechange load', function(){
         if (this.complete) $(this).fadeIn(300);
      });
   });
});