使用Javascript從圖像到圖像(不是圖像到白色到圖像)的淡入淡出

[英]Fading from image to image (not image to white to image) using Javascript


I have a "slideshow" type of function where images fade in and out to each other. It works fine, but when it fades, it is fading the first picture out to white and then the second picture fades in. What I want is for the first image to fade right into the second (with no empty white background in between). Can I do this?

我有一個“幻燈片”類型的功能,其中圖像相互淡入和淡出。它工作正常,但是當它消失時,它會將第一張圖片淡出為白色,然后第二張圖片逐漸消失。我想要的是第一張圖像漸漸淡入第二張圖片(中間沒有空的白色背景)。我可以這樣做嗎?

Here is an example: http://jsfiddle.net/aegtjm5y/5/

這是一個例子:http://jsfiddle.net/aegtjm5y/5/

image

<img id="image1" src="http://9pixs.com/wp-content/uploads/2014/06/dog-pics_1404159465.jpg" style="width: 100%;">

JS

var curIndex = 0;
var src = ['/images/IMG_20140907_203614.jpg', 'http://9pixs.com/wp-content/uploads/2014/06/dog-pics_1404159465.jpg', 'http://cvcl.mit.edu/hybrid/cat2.jpg'];
var fadeTimeInMilliseconds = 2000;
var waitTimeInMilliseconds = 1000;

$(document).ready(function(){
    switchImageAndWait(true);
});

function switchImageAndWait(fadeOut2){
    if(fadeOut2){
        setTimeout(fadeOut, waitTimeInMilliseconds);
    }else{
        var index = Math.floor((Math.random()*src.length))
        if(curIndex == index){
            index++;
            if(index >= src.length){
                index-=2;
            }
        }
        curIndex = index;
        $("#image1").attr("src", src[index]);
        fadeIn();
    }
}

function fadeOut(){
    $("#image1").fadeTo( fadeTimeInMilliseconds, 0 , function() { switchImageAndWait(false); });
}

function fadeIn(){
    $("#image1").fadeTo( fadeTimeInMilliseconds, 1 , function() { switchImageAndWait(true); });
}

1 个解决方案

#1


1  

Edit: "Can I do this?" - No. You can't do this using only one image element.

編輯:“我可以這樣做嗎?” - 否。您不能僅使用一個圖像元素執行此操作。

What you basically need is two images one on top of the other.

你基本上需要的是兩個圖像,一個在另一個上面。

I edited your fiddle and it's working fine: JSFiddle

我編輯了你的小提琴,它工作正常:JSFiddle

So basically I added another img element and set the position of the images to be absolute (so they are overlaying).

所以基本上我添加了另一個img元素並將圖像的位置設置為絕對(因此它們重疊)。

<img id="image2" src="http://cvcl.mit.edu/hybrid/cat2.jpg" style="width: 100%;position: absolute;">

I updated the javascript stuff so the images get changed in both fadeIn and fadeOut "events". The principle is that the upper image gets faded out and faded In. When it's not visible you change the src of it. And when it is visible you change the src of bottom image.

我更新了javascript的東西,以便在fadeIn和fadeOut“events”中更改圖像。原理是上部圖像淡出並淡入。當它不可見時,你改變它的src。當它可見時你改變了底部圖像的src。

I can't think of better solution now. Hope this helps..

我現在想不出更好的解決方案。希望這可以幫助..


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/09/29/5a86a8106401c1dbca0afbe4b383c426.html



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