如何防止 CSS 动画在第二个悬停动画后重新运行

How to prevent a CSS animation from rerunning after a second hover animation

我在加载页面时以及将鼠标悬停在元素上时有一个动画。我的问题是悬停动画何时完成第一个重播。有什么办法可以stop/prevent不重播吗?

img {
    height: 40px;
    width: auto;
    position: absolute;
    animation-name: test1;
    animation-duration: 4s;
}
img:hover {
    animation-name: test2;
    animation-duration: 4s;
}
@keyframes test1 {
    from {height: 40px}
    to {height: 80px}
}
@keyframes test2 {
    from {height: 40px}
    to {height: 80px}
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <img src="https://media.discordapp.net/attachments/874191575004094524/946077618992738375/grey.png" alt="">
</body>
</html>

  • animation-* 属性(如 animation:animation-name:animation-duration: 等)是 multi-valued 属性,就像 background-image.

  • 当元素的 multi-value 属性 的有效值发生变化时(例如,设置一个全新的 background-image:animation: 当元素属性) 已经有多个值,那么 CSS 将 替换整个列表 的值。

  • 因此,如果一个规则集 animation-name: foo; 和另一个(临时应用的)规则集 animation-name: bar; 那么这算作删除 foo 并添加 bar ,而不是简单地将 bar 添加到现有的动画列表中。

  • 和CSS动画(默认)在添加时启动,删除后无法控制

  • 因此,在您的情况下,test1 动画重新启动,因为您的 :hover 规则 删除了 test1 动画img 的 animation-list(并添加 test2),然后当离开 :hover 状态时 test1 动画是 re-added,这使得它再次重新启动 test1 动画。

解决方法是 不从 :hover 状态移除 test1 动画,如下所示:

    img {
        animation-name: test1;
        animation-duration: 4s;
    }
    img:hover {
        animation-name: test1, test2;
        animation-duration: 4s, 4s;
    }

演示:

  • 为了清晰起见,我已将 test1 重命名为 onLoad,将 test2 重命名为 onHover,并将 sped-up 动画重命名为 1-2s(从 4s) .
  • 图片会旋转 on-load,悬停时会变大。
  • 请注意,停止悬停图像后,它不会再次旋转。

img {
    height: 40px;
    width: auto;
    position: absolute;


    animation-name: onLoad;
    animation-duration: 1s;
}
img:hover {
    animation-name: onLoad, onHover;
    animation-duration: 1s, 2s;
}
@keyframes onLoad {
    from { transform: rotate(0deg); }
    to   { transform: rotate(179deg); }
}
@keyframes onHover {
    from { height: 40px; width: 40px; }
    to   { height: 80px; height: 80px; }
}
<img src="https://i.stack.imgur.com/pVgz6.png" alt="">