仅运行一次CSS3动画(在页面加载时)

bus*_*ens 46 css css3 css-animations

我正在制作一个由CSS3驱动的简单登陆页面.为了让它看起来很棒,有一个<a>很大的问题:

@keyframes splash {
    from {
        opacity: 0;
        transform: scale(0, 0);
    }
    50% {
        opacity: 1;
        transform: scale(1.1, 1.1);
    }
    to {
        transform: scale(1, 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

为了让它更加精彩,我添加了一个悬停动画:

@keyframes hover {
    from {
        transform: scale(1, 1);
    }
    to {
        transform: scale(1.1, 1.1);
    }
}
Run Code Online (Sandbox Code Playgroud)

但问题来了!我分配了这样的动画:

a {
    /* Some basic styling here */

    animation: splash 1s normal forwards ease-in-out;
}
a:hover {
    animation: hover 1s infinite alternate ease-in-out;
}
Run Code Online (Sandbox Code Playgroud)

一切都运行得很好:<a>飞溅到用户脸上,当他徘徊时有一个很好的振动.一旦用户模糊,<a>平滑的东西突然结束并<a>重复splash动画.(这对我来说是合乎逻辑的,但我不想要它)如果没有一些JavaScript类Jiggery Pokery,有没有办法解决这个问题?

bus*_*ens 27

经过数小时的谷歌搜索:不,没有JavaScript,这是不可能的.该animation-iteration-count: 1;内部保存在animationshothand属性,它被重置了和覆盖:hover.当我们模糊<a>并释放:hover旧阶级重新应用,因此再次重置animation属性.

遗憾的是,没有办法在元素状态之间保存某些属性状态.

你必须使用JavaScript.

  • @Dchris只需添加一个类似"animate-this"的类,并在动画结束后将其删除. (3认同)
  • 尝试将 `:not(:hover)` 添加到飞溅动画的选择器中。 (2认同)

Str*_*lok 26

如果我正确理解你只想在你A必须添加时播放动画

animation-iteration-count: 1
Run Code Online (Sandbox Code Playgroud)

为了风格a.


But*_*uri 20

它可以通过一些额外的开销来完成.

只需将链接包装在div中,然后分离动画即可.

html ..

<div class="animateOnce">
    <a class="animateOnHover">me!</a>
</div>
Run Code Online (Sandbox Code Playgroud)

..和css ..

.animateOnce {
    animation: splash 1s normal forwards ease-in-out;
}

.animateOnHover:hover {
    animation: hover 1s infinite alternate ease-in-out;
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*dus 19

我刚刚开始使用Firefox和Chrome.您只需根据需要添加/删除以下类.

.animateOnce {
  -webkit-animation: NAME-OF-YOUR-ANIMATION 0.5s normal forwards; 
  -moz-animation:    NAME-OF-YOUR-ANIMATION 0.5s normal forwards;
  -o-animation:      NAME-OF-YOUR-ANIMATION 0.5s normal forwards;
}
Run Code Online (Sandbox Code Playgroud)


小智 6

只需使用

animation: hover 1s ease-in-out forwards;
Run Code Online (Sandbox Code Playgroud)

  • 虽然此代码片段可以解决问题,但它没有解释为什么或如何回答问题。请[包括对您的代码的解释](//meta.stackexchange.com/q/114762/269535),因为这确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而那些人可能不知道您建议代码的原因。 (3认同)