首页 > 解决方案 > 同一元素上的 CSS 多个动画

问题描述

我的页面上有一个单曲<div>。红色方块,我想对其应用 2 个动画:

  1. 在页面加载时移动这个方块
  2. 在鼠标悬停时更改正方形的颜色

这是代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
    .animation {
        width: 150px;
        height: 150px;
        background-color: red;
        animation-name: anim;
        animation-duration: 3s;
        animation-fill-mode: forwards;
    }

    .animation:hover {
        animation-name: hover;
        animation-duration: 1s;

    }

    @keyframes anim {
        from {
        }
        30% {
            transform: translateX(100px);
        }
        70% {
            transform: translate(100px, 100%);
            /*background-color: blue;*/
        }
        100% {
            transform: translate(100px, 100%) scale(2, 2) rotate(145deg);
        }
    }

    @keyframes hover {
        from {
        }
        to {
            background:yellow;
        }
    }
</style>
</head>
<body>
<div class="animation">
</div>
</body>
</html>

https://jsfiddle.net/tbqj4goy/

问题在于,当我将嘴悬停时,第一个动画会中断并从头开始。

有什么想法可以让这些动画毫无问题地协作吗?

标签: htmlcsscss-animations

解决方案


.animation {
    width: 150px;
    height: 150px;
    background-color: red;
    animation-name: anim;
    animation-duration: 3s;
    animation-fill-mode: forwards;
    transition: 1s;
}

.animation:hover {
    background-color: yellow;
    transition: 1s;
}

@keyframes anim {
    from {}

    30% {
        transform: translateX(100px);
    }

    70% {
        transform: translate(100px, 100%);
        /*background-color: blue;*/
    }

    100% {
        transform: translate(100px, 100%) scale(2, 2) rotate(145deg);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="animation">
</div>
</body>
</html>


推荐阅读