jQuery使用淡入淡出效果更改圖像src

[英]jQuery Change Image src with Fade Effect


I'm trying to create an effect where you click on a thumbnail image, and the link to the thumbnail will replace the main image, but fade it in. This is the code I'm currently using:

我正在嘗試創建一個效果,您單擊縮略圖圖像,縮略圖的鏈接將替換主圖像,但淡入其中。這是我目前使用的代碼:

$(".thumbs a").click(function(e) {
    e.preventDefault();
    $imgURL = $(this).attr("href");
    $(".boat_listing .mainGallery").fadeIn(400, function() {
        $(".boat_listing .mainGallery").attr('src',$imgURL);
    });
});

This works and replaces the image without a fade effect. What do I need to change to get the fadeIn effect to work?

這適用於替換圖像而沒有淡入淡出效果。我需要更改什么才能使fadeIn效果起作用?

4 个解决方案

#1


71  

You have to make it fadeOut() first, or hide it.

你必須首先使它成為fadeOut(),或隱藏它。

Try this :

嘗試這個 :

$(".thumbs a").click(function(e) {
    e.preventDefault();
    $imgURL = $(this).attr("href");
    $(".boat_listing .mainGallery")
        .fadeOut(400, function() {
            $(".boat_listing .mainGallery").attr('src',$imgURL);
        })
        .fadeIn(400);
});

It should fadeOut the image, then change the src when it's hidden, and then fadeIn.

它應該淡出圖像,然后在隱藏時更改src,然后淡入。

Here's a jsFiddle example.

這是一個jsFiddle示例。

#2


29  

I thing instead of using FadeIn and fadeOut, its better to use fadeTo functionality as fadeIn and fadeOut created a time gap between them for few micro-seconds.

我不是使用FadeIn和fadeOut,而是更好地使用fadeTo功能作為fadeIn和fadeOut在它們之間創建了一個時間間隔幾微秒。

I have used above code from Sylvain : thanks to him

我使用了Sylvain的上述代碼:感謝他

$("#link").click(function() {

  $("#image").fadeTo(1000,0.30, function() {
      $("#image").attr("src",$("#link").attr("href"));
  }).fadeTo(500,1);
  return false;
});

#3


0  

You cannot fade-in something that is already at 100% alpha :)

你不能淡入已經達到100%alpha的東西:)

In other words, you either fade it out or hide it, and then fade it in.

換句話說,你要么將其淡出或隱藏它,然后將其淡入。

I made this example, basically, I hide it and then fade it:

我做了這個例子,基本上,我隱藏它然后淡化它:

http://jsfiddle.net/uGFMt/

http://jsfiddle.net/uGFMt/

#4


0  

I reproduced the given samples above. It gives a strange flickering, which I found that it waits for image to load after it's opacity is restored to 1. I modified the code by Sandeep.

我復制了上面給出的樣本。它給出了一個奇怪的閃爍,我發現它在不透明度恢復到1后等待圖像加載。我修改了Sandeep的代碼。

$("#link").click(function() {

$("#image").fadeTo(1000,0.30, function() {
  $("#image").attr("src",$("#link").attr("href"));
  $("#image").on('load', function(){
    $("#image").fadeTo(500,1);
  });
 });
 return false;
});`

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/05/12/7def853aed59d9bcfc9c44b4f4b91c1a.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com