we can use requestAnimationFrame to reset animation and reverse it when browser paints in next frame.
Also use onmouseenter and onmouseout event handlers to reverse animation direction
Any rAFs queued in your event handlers will be executed in the ?same frame?. Any rAFs queued in a rAF will be executed in the next frame?.
function fn(el, isEnter) {_x000D_
el.className = "";_x000D_
requestAnimationFrame(() => {_x000D_
requestAnimationFrame(() => {_x000D_
el.className = isEnter? "in": "out";_x000D_
});_x000D_
}); _x000D_
}
_x000D_
.in{_x000D_
animation: k 1s forwards;_x000D_
}_x000D_
_x000D_
.out{_x000D_
animation: k 1s forwards;_x000D_
animation-direction: reverse;_x000D_
}_x000D_
_x000D_
@keyframes k_x000D_
{_x000D_
from {transform: rotate(0deg);}_x000D_
to {transform: rotate(360deg);}_x000D_
}
_x000D_
<div style="width:100px; height:100px; background-color:red" _x000D_
onmouseenter="fn(this, true)"_x000D_
onmouseleave="fn(this, false)" _x000D_
></div>
_x000D_