opacity fade 仅适用于调试模式

opacity fade only works in debug mode

我正在尝试使用 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,顶部和底部。加载时我将顶部设置为 0 不透明度。 (为上面的脚本设置它)。

当我编写代码时,它似乎并没有淡出,它只是突然出现......直到我在 var elem = document.getElementById("top"); 行之前放置一个警报,然后它工作得很好,所以我 运行 它处于调试(控制台?)模式,如果我一次单步执行它,它也能完美运行。

有谁知道为什么会这样?我需要某种延迟才能让 t运行sition 发生吗?

像这样使用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
}