如何控制无限 CSS 动画(第 1 部分,共 2 部分)
Applying an infinite animation to an element is a simple task. For example, to make an element rotate indefinitely, you add the code below, and it’s done.
对元素应用无限动画是一个简单的任务。例如,要使元素无限旋转,你添加下面的代码,就完成了。
.box {
animation: rotate 5s infinite linear;
}
@keyframes rotate {
to { rotate: 1turn; }
}Code language: CSS (css)
Now, what if I ask you to interact with that rotation? Accelerate it, slow it down, stop it smoothly, etc. It would be tricky, right? The only thing we can easily do is to pause the animation using:
现在,如果我让你交互那个旋转呢?加速它,减慢它,平滑停止它,等等。这会很棘手,对吧?我们唯一能轻易做的是使用以下方式暂停动画:
animation-play-state: paused;Code language: CSS (css)
In this series of articles, we will learn much more than just how to pause an infinite animation.
在这一系列文章中,我们将学习的内容远不止如何暂停无限动画。
Let’s jump straight into the first example.
让我们直接进入第一个示例。
Consider the following code:
考虑以下代码:
.box {
animation:
rotate 5s linear infinite,
rotate 5s linear infinite paused;
animation-composition: add;
}
.box:hover {
animation-play-state: running;
}
@keyframes rotate {
to { rotate: 1turn; }
}
Code language: CSS (css)
I am defining the same animation twice, with the second one paused. On hover, both are running, resulting in faster rotation!
我定义了两次相同的动画,第二个暂停。在悬停时,两者都运行,导致更快的旋转!
Cool, right? This trick was made possible using animation-composition: add. A quick look at the MDN page explains everything:
酷吧?这个技巧使用animation-composition: add得以实现。快速查看MDN 页面即可了解一切:
The
animation-compositionCSS property specifies the composite operation to use when multiple animations affect the same property simultaneously.
animation-compositionCSS 属性指定了当多个动画同时影响同一属性时要使用的复合操作。
Then
然后
add
addThe effect value builds on the underlying value of the property. This operation produces an additive effect
效果值基于属性的底层值。此操作产生一种累加效果
We are applying the same animation twice, so they add up. Initially, only one rotation runs, and on hover, the second starts, making the overall rotation faster.
我们应用了相同的动画两次,因此它们会叠加。最初,只有一个旋转运行,悬停时第二个开始,从而使整体旋转更快。
The result is similar to dividing the du...