gpt4 book ai didi

css - 是否可以使用单个 @keyframes 规则在两个方向上播放动画?

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:22 25 4
gpt4 key购买 nike

我想使用单个 @keyframes 规则将元素从一种状态动画化到另一种状态,然后在执行操作时返回到原始状态(使用相同的动画)。我看到使用 animation-direction: reverse; 是一种反向播放动画的方法。但是,当我尝试使用它时,元素上的过渡消失了。如果我设置一个新的 @keyframes 与相反的状态它工作正常。

在这种情况下,animation-direction 有什么意义?我是不是误会了什么?

有没有一种方法可以在不丢失过渡的情况下使用单个 @keyframes 规则在两个方向上播放动画?我不能使用transition,我需要animation

这是一个可以玩的例子(悬停在方 block 上):

div {
width: 100px;
height: 100px;
animation: fade 0.6s ease-in-out forwards;
margin: 15px;
display: inline-flex;
align-items: center;
justify-content: center;
color: white;
}

#box-1:hover {
animation: fade 0.6s ease-in-out forwards;
animation-direction: reverse;
}

#box-2:hover {
animation: fadeReverse 0.6s ease-in-out forwards;
}

@keyframes fade {
0% { background: red; }
100% { background: blue; }
}

@keyframes fadeReverse {
0% { background: blue; }
100% { background: red; }
}
<div id="box-1">:(</div>
<div id="box-2">:)</div>

最佳答案

这是因为您对悬停时的元素应用了与元素默认状态下的动画相同的动画。

因此该元素已经具有默认方向的动画,但随后您再次反向应用它。但这是行不通的。我真的不知道为什么会这样。但是在一个元素上应用相同的动画两次是行不通的。所以你需要 2 个不同的关键帧。

您可以使用reverse 动画或复制现有动画并将其与direction: reverse 一起使用

在这里阅读更多 restart animation

more info here

another article here

如果您真的只想使用 1 个动画,这可以通过删除和添加“animate-me”类来使用 javascript 来解决。但还是不太理想

div {
width: 100px;
height: 100px;
animation: fade 0.6s ease-in-out forwards;
margin: 15px;
display: inline-flex;
align-items: center;
justify-content: center;
color: white;
}

#box-1:hover {
animation: fade2 0.6s ease-in-out forwards;
animation-direction: reverse;
}

#box-2:hover {
animation: fadeReverse 0.6s ease-in-out forwards;
}

@keyframes fade {
0% { background: red; }
100% { background: blue; }
}
@keyframes fade2 {
0% { background: red; }
100% { background: blue; }
}

@keyframes fadeReverse {
0% { background: blue; }
100% { background: red; }
}
<div id="box-1">:(</div>
<div id="box-2">:)</div>

关于css - 是否可以使用单个 @keyframes 规则在两个方向上播放动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58063669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com