离开鼠标后CSS过渡到原始状态

tro*_*lic 5 html javascript css css-transitions css-animations

编辑:这与本文不同,如何将鼠标悬停如何在鼠标移出时反转动画。不同之处在于,在这种情况下,过渡状态(进展程度)至关重要,这与前面提到的完全忽略过渡的职位不同。

TL; DR:动画结束后,如何将元素动画化/转换回其原始状态?

你好,

我正在尝试制作动画面板,以使其在悬停时“浮动”。我的问题是鼠标离开面板,而不是过渡回其原始状态,而是立即跳回。

可以在下面的代码段中找到它的简化版本。

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);
  }
}
Run Code Online (Sandbox Code Playgroud)
<html>
  <head>
    <title>animate to orignal position</title>
  </head>
  <body>
    <div id='box'></div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

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

所以我的问题是:有没有一种方法可以让盒子过渡到其原始状态,最好不要使用JavaScript(尽管所有建议都值得赞赏)。

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

谢谢。

sil*_*non 5

你将不得不使用 JavaScript 和 CSS Transitions:

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')
})
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
<html>
  <head>
    <title>animate to orignal position</title>
  </head>
  <body>
    <div id='box'></div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)