简体   繁体   中英

opacity fade only works in debug mode

I am trying to add a fade between two images using 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.
}

Basically, I have 2 divs, top and bottom. on load I set top to 0 opacity. (setting it up for the above script).

When I wrote the code it didn't seem fade out, it just popped into place.... until I put an alert right before the var elem = document.getElementById("top"); line, then it worked perfectly, so I ran it in debug (console?) mode and it works perfectly as well if I step through it one line at a time.

Does anyone know why this would happen? Do I need some kind of delay to allow the transition to happen?

use setTimeout like this

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM