2015-06-24 37 views
1

我試圖添加使用javascript兩個圖像之間的淡入淡出:不透明度淡出只能在調試模式

function swap(test){ 

    if(test==2){ 

    document.getElementById("top").innerHTML = "<img src=\"_images/"+showList[showIndex][3]+".jpg\" width=\"400\" />"; // Sets top invisible div to old picture 

    showIndex++; 

    var elem = document.getElementById("top"); 
    elem.style.transition = ""; 
    elem.style.opacity =1; // makes old picture visible 

     document.getElementById("bottom").innerHTML = "<img src=\"_images/"+showList[showIndex][3]+".jpg\" width=\"400\" />"; 
    } // Set's bottom div to New picture 

    var elem = document.getElementById("top"); 
    elem.style.transition = "opacity 0.5s linear 0s"; 
    elem.style.opacity = 0; // fades out top picture to reveal new bottom pic. 
} 

基本上,我有2個的div,頂部和底部。在負載上,我將top設置爲0不透明度。 (爲上面的腳本設置它)。

當我編寫代碼時,它似乎不會淡出,它只是彈出到位......直到我在var elem = document.getElementById("top");行之前發出警報,然後它完美運行,所以我在debug(控制檯?)模式,如果我一次只讀一行,它也可以很好地工作。

有誰知道爲什麼會發生這種情況?我是否需要某種延遲來實現過渡?如果你把連同所需的HTML/CSS/JS提琴

+0

將是有益的。 http://jsfiddle.net –

回答

2

使用setTimeout這樣

function swap(test){ 

    if(test==2){ 

    document.getElementById("top").innerHTML = "<img src=\"_images/"+showList[showIndex][3]+".jpg\" width=\"400\" />"; // Sets top invisible div to old picture 

    showIndex++; 

    var elem = document.getElementById("top"); 
    elem.style.transition = ""; 
    elem.style.opacity =1; // makes old picture visible 

     document.getElementById("bottom").innerHTML = "<img src=\"_images/"+showList[showIndex][3]+".jpg\" width=\"400\" />"; 
    } // Set's bottom div to New picture 
setTimeout(function(){ 
    var elem = document.getElementById("top"); 
    elem.style.transition = "opacity 0.5s linear 0s"; 
    elem.style.opacity = 0; // fades out top picture to reveal new bottom pic. 
    }, 5000);//here time interval is 5 seconds 
} 
+0

謝謝西德。它完美的作品。我將超時功能降低到1(毫秒),並且仍然完美。這是讓這種類型的函數起作用的標準方式,還是你猜測基於我提到的延遲? – user2067101

+0

@ user2067101:setTimeout方法在給定的持續時間後執行給定的代碼,因爲您希望執行淡入淡出效果。這是最佳解決方案。如果答案適合您,請將其加註並標記爲答案。 –

相關問題