即使用户停止悬停,如何确保 CSS 动画完成?

How do I ensure a CSS animation completes even if the user stops hovering?

某些动画可能会以某种方式移动元素,如果用户没有用鼠标完美地跟随它,动画将永远不会完成。如何确保动画在用户完全悬停后完成?

如果在动画完成时它们没有悬停,我希望它撤消动画并返回非悬停状态,但如果未完成,请先完成它。

如果没有 javascript,有什么办法可以做到这一点吗?

我不知道有什么方法可以在没有 JavaScript 的情况下以一种干净的方式执行此操作,但您通常至少可以将(不可见的)悬停目标保持在一个位置,同时其他元素移动作为动画的一部分。

@keyframes orbit {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}

.circle {
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: sans-serif;
  color: white;
  width: 120px;
  height: 120px;
  border-radius: 9999px;
  transform-origin: 200% 50%;
}

body > .circle {
  margin: 120px;
}

.must-follow {
  background-color: green;
}

.must-follow:hover {
  animation: orbit 20s ease;
}

.can-follow-inner {
  background-color: blue;
}

.can-follow:hover .can-follow-inner {
  animation: orbit 20s ease;
}

.no-follow {
  position: relative;
}

.no-follow-target {
  position: absolute;
}

.no-follow-after {
  background-color: red;
  pointer-events: none;
}

.no-follow-target:hover + .no-follow-after {
  animation: orbit 20s ease;
}
<div class="circle must-follow">follow me</div>

<div class="circle can-follow">
  <div class="circle can-follow-inner">follow or don’t</div>
</div>

<div class="circle no-follow">
  <div class="circle no-follow-target"></div>
  <div class="circle no-follow-after">don’t follow</div>
</div>