【问题标题】:Immediately reverse CSS3 animation立即反转 CSS3 动画
【发布时间】:2014-04-17 15:26:19
【问题描述】:

当我将 .shown 类添加到我的 #overlay 时,我希望不透明度淡入 2 秒,然后立即反转并淡出 2 秒,创建一种“闪烁”效果。

我尝试只删除该类,但根本没有显示任何动画。这是我的示例标记/CSS:

HTML:

<div id="outer">
    This is some text
    <div id="overlay"></div>
</div>

CSS:

#overlay {
    ...
    opacity: 0;
    transition: opacity 2s ease-in-out;
}
#overlay.shown {
    opacity: 0.3;
}

尝试的 JS:

// Wait 2 seconds from page load...
setTimeout(function() {
    // Add shown class to trigger animation
    document.getElementById("overlay").classList.add("shown");
    // Want to remove the class and hoped this would reverse the animation...
    // it doesn't
    document.getElementById("overlay").classList.remove("shown");
}, 2000);

jsFiddle

【问题讨论】:

  • 你能用 jquery 做同样的事情吗?
  • @DholakiyaAnkit 不,很遗憾没有。
  • 尝试在 #overlay.shown 选择器中包含过渡属性。

标签: javascript html css


【解决方案1】:

使用带有关键帧的 css 动画

@keyframes myFlash
{
0%   {opacity:0;}
50%  {opacity:0.3;}
100% {opacity:0;}
}

@-webkit-keyframes myFlash /* Safari and Chrome */
{
0%   {opacity:0;}
50%  {opacity:0.3;}
100% {opacity:0;}
}

#overlay {
    ...
    opacity: 0;
}
#overlay.shown {
animation:myFlash 2s;
-webkit-animation:myFlash 2s; /* Safari and Chrome */
}

【讨论】:

  • 您不需要使用此解决方案删除类,只需添加它,当您需要闪烁时。
【解决方案2】:

看起来你可以在第一个动画完成后使用第二个超时..

// Wait 2 seconds from page load...
setTimeout(function() {
    // Animate Forward
    document.getElementById("overlay").classList.add("shown");
    setTimeout(function(){
        // Animate Back
        document.getElementById("overlay").classList.remove("shown");
    },2000);
}, 2000);

【讨论】:

    【解决方案3】:

    为了实现您的输出,我做了很多更改,请检查以下代码

    Your css
    #outer {
        width: 100px;
        height: 100px;
        position: relative;
    }
    #overlay {
        top: 0;
        left: 0;
        position: absolute;
        width: 100%;
        height: 100%;
        background: #336699;
        opacity: 0;
        transition: opacity 2s ease-in-out;
    }
    #overlay.shown {
        display: block;
        opacity: 0.5;
    }
    

    你的js

    setTimeout(function() {
        $("#overlay").addClass("shown");
       var def = $('#overlay').promise();
        def.done(
           function () {
              $('body').stop().delay(5000).queue(function(){
            $("#overlay").removeClass("shown");
        });
    
        });
    
    
    }, 2000);
    

    第一个和第二个之间没有延迟,所以它将如何显示你所做的动画

    请查看工作演示.....Demo

    【讨论】:

    • Javascript可以用吗?
    • 技术上是的,但我正在寻找的是 Taimour 的解决方案——纯 CSS 解决方案
    • 因为您为未标记为此类的问题提供了 jQuery 答案。因此,正如否决按钮所说,这对我没有帮助。这也不是解决这个问题的正确方法。为不到 10 行 CSS 就可以实现的东西添加 90k 的库
    猜你喜欢
    • 2015-11-06
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多