【问题标题】:How do I ensure a CSS animation completes even if the user stops hovering?即使用户停止悬停,如何确保 CSS 动画完成?
【发布时间】:2021-12-13 04:37:12
【问题描述】:

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

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

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

【问题讨论】:

  • 你能举个例子吗?
  • 我不知道在没有 JavaScript 的情况下以干净的方式执行此操作的方法,但您通常至少可以将(不可见的)悬停目标保持在一个位置,而其他一些元素移动为动画的一部分。
  • 据我所知纯 CSS 做不到,你需要使用一点 JavaScript:stackoverflow.com/questions/7694323/…
  • 与一些 CSS hack 相关:stackoverflow.com/a/67797260/8620333
  • @Ry- 这对我的问题来说是一个很好的解决方案。如果您想通过一个简单的示例将其发布为答案(例如,100px div 上的 transitionX(500px)),我会接受它。

标签: javascript html css css-animations


【解决方案1】:

我不知道在没有 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>

【讨论】:

    猜你喜欢
    • 2014-06-02
    • 1970-01-01
    • 2021-01-02
    • 2019-05-06
    • 2021-03-16
    • 2021-04-29
    • 2015-06-09
    • 1970-01-01
    • 2022-10-06
    相关资源
    最近更新 更多