CSS mouseleave 后过渡到原始状态

CSS transition to original state after mouseleave

编辑: 这与 post、How to reverse an animation on mouse out after hover 不同。不同之处在于,在这种情况下,过渡状态(它进展了多远)是必不可少的,这与前面提到的完全忽略它的 post 不同。

TL;DR: 如何在动画结束后 animate/transition 将元素恢复到原始状态?

您好,

我正在尝试制作动画面板,以便它们在悬停时 "float"。我的问题是鼠标离开面板,而不是转换回其原始状态,它会立即跳回。

可以在下面的代码片段中找到一个非常简化的版本。

body {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

div {
  width: 50px;
  height: 50px;
  background-color: red;
}

div:hover {
  animation: float 2s infinite ease;
}

@keyframes float {
  0%, 100% {
    transform: none;
  }
  50% {
    transform: translateY(-20px);
  }
}
<html>
  <head>
    <title>animate to orignal position</title>
  </head>
  <body>
    <div id='box'></div>
  </body>
</html>

如您所见,浮动它会触发类似于浮动动作的平滑动画,但是,当鼠标离开框时它会突然中断并且动画停止。

所以我的问题是:有没有办法让盒子恢复到原来的状态,最好不使用 JavaScript(尽管所有建议都值得赞赏)。

(这可能已经在网上某个地方得到了回答,如果是这样,那么我真的很抱歉,但我一直无法找到解决我的问题的合适方法。如果你找到请添加重复项适用的解决方案。)

谢谢。

您将不得不使用 JavaScript 和 CSS 转换:

var box = document.getElementById('box')
var timer

box.addEventListener('mouseenter', function () {
  box.classList.add('up')
  timer = setInterval(function () {
    box.classList.toggle('up')
  }, 1000)
})

box.addEventListener('mouseleave', function () {
  clearInterval(timer)
  box.classList.remove('up')
})
body {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

div {
  width: 50px;
  height: 50px;
  background-color: red;
  transition: transform 1s ease;
}

div.up {
  transform: translateY(-20px);
}
<html>
  <head>
    <title>animate to orignal position</title>
  </head>
  <body>
    <div id='box'></div>
  </body>
</html>