javascript - opacity fade 仅适用于 Debug模式

标签 javascript css opacity

我正在尝试使用 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"); 之前放置了一个警报; 行,然后它工作得很好,所以我在调试(控制台?)模式下运行它,如果我一次单步执行它,它也能完美地工作。

有人知道为什么会这样吗?我是否需要某种延迟才能实现过渡?

最佳答案

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

关于javascript - opacity fade 仅适用于 Debug模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31028877/

相关文章:

jquery - 单击此菜单项时如何更改其他菜单项的不透明度?

javascript - Three.js - 变换控件

javascript - 尝试在 Knockout 中的 css 数据绑定(bind)中使用 &&

javascript - 使用字典将返回的状态映射到选择下拉列表以进行过滤,会产生我试图删除的重复项并将唯一键附加到

html - 缩放时发生 CSS 奇怪的事情

html - 如何让我的菜单响应?

CSS 线性渐变和 Canvas 线性渐变与不透明度设置不同

html - <nav> 元素透明,没有任何先前的不透明度/透明度调整 HTML/CSS

javascript - 如何防止打开 IE 中的默认选项?

javascript - Css 和 Javascript 在组件 Angular 6 中不起作用