【问题标题】:opacity fade only works in debug modeopacity fade 仅适用于调试模式
【发布时间】:2016-01-25 16:21:24
【问题描述】:

我正在尝试使用 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"); 行之前发出警报,然后它运行良好,所以我在调试中运行它(控制台?)模式,如果我一次通过一行,它也能完美运行。

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

【问题讨论】:

  • 如果您将所需的 HTML/CSS/JS 放在一起,将会很有帮助。 jsfiddle.net

标签: javascript css opacity


【解决方案1】:

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

【讨论】:

  • 谢谢希德。它完美地工作。我将超时功能降低到 1(毫秒?),它仍然可以正常工作。这是使此类功能正常工作的标准方法,还是您根据我提到的延迟猜到了?
  • @user2067101: setTimeout 方法在给定的持续时间后执行给定的代码,因为你想做淡入淡出效果。这是最好的解决方案。如果答案对您有用,请点赞并将其标记为答案。
猜你喜欢
  • 1970-01-01
  • 2016-08-31
  • 1970-01-01
  • 2014-09-16
  • 2012-10-08
  • 1970-01-01
  • 2014-12-19
  • 1970-01-01
  • 2018-04-20
相关资源
最近更新 更多