我正在尝试在 mouseover
事件上应用动画(工作正常)以及具有 reverse
和 backwards
属性的相同动画来播放它返回 mouseleave
。但是第二部分不能正常工作。最后,我希望动画在 mouseover
上向前播放,在 mouseleave
上向后播放。如果有一种方法可以从上一个动画停止的地方应用下一个动画,请将其包含在您的答案中。这是我的代码:
const target = document.getElementById("animated");
target.addEventListener("mouseover", animateForward);
target.addEventListener("mouseout", animateBackward);
function animateForward() {
target.style.animation = 'custom 1.6s forwards';
}
function animateBackward() {
target.style.animation = 'custom 1.6s reverse backwards';
}
/* Safari 4.0 - 8.0 */
@-webkit-keyframes custom {
25% {
border-radius: 50% 0 0 0;
}
50% {
border-radius: 50% 50% 0 0;
}
75% {
border-radius: 50% 50% 50% 0;
}
100% {
border-radius: 50% 50% 50% 50%;
background-color: violet;
}
}
/* Standard syntax */
@keyframes custom {
25% {
border-radius: 50% 0 0 0;
}
50% {
border-radius: 50% 50% 0 0;
}
75% {
border-radius: 50% 50% 50% 0;
}
100% {
border-radius: 50% 50% 50% 50%;
background-color: violet;
-moz-transform: rotate(180deg);
-webkit-transform: rotate(180deg);
-o-transform: rotate(180deg);
-ms-transform: rotate(180deg);
transform: rotate(180deg);
}
}
div {
border: 1px black solid;
width: 100px;
height: 100px;
margin: 50px;
}
<div id="animated"></div>
这里是 JsFiddle .
最佳答案
对于纯 CSS 解决方案,保留 @keyframes
,并改用 transitions
。在处理 :hover
时,转换几乎总是您真正需要的。
例如,您的动画的所有属性都可以独立设置,因此它们可以有自己的过渡规则。
因此您的动画可以通过以下转换进行转换,其中每个关键帧都已替换为三重奏 transition-property
-transtion-duration
-transition-延迟
。
div {
border: 1px black solid;
width: 100px;
height: 100px;
margin: 50px;
/* define all the props */
transition-property:
transform,
background-color,
border-top-left-radius,
border-top-right-radius,
border-bottom-right-radius,
border-bottom-left-radius;
/* set their duration independently */
transition-duration: 1.6s, 1.6s, 0.4s, 0.4s, 0.4s, 0.4s;
/* same for delays */
transition-delay: 0s, 0s, 0s, 0.4s, 0.8s, 1.2s;
}
div:hover{
border-radius: 50%;
background-color: violet;
transform: rotate(180deg);
}
<div id="animated"></div>
关于javascript - 反向向后动画不适用于 mouseout 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45579674/