【问题标题】:Hover animation makes initial animation rerun after mouse out悬停动画使初始动画在鼠标移出后重新运行
【发布时间】:2022-01-25 01:33:26
【问题描述】:

我有一个元素,动画在开始时开始一次,并且在悬停时无限运行动画。

当鼠标熄灭时,无限动画停止但初始重新运行,如何防止?

这是一个例子,我不希望鼠标熄灭时重新运行 kf-initial 动画。

谢谢!

.foo {
  margin: auto;
  margin-top: 100px;
  padding: 1em;
  width: fit-content;
  border: solid 1px black;
  background: red;
  color: white;
  font-size: 2em;
    
  /* The initial animation */
  animation: kf-initial 2s;
}

.foo:hover {
  /* The infinite animation */
  animation: kf-hover 10s infinite;
}

@keyframes kf-initial {
  from {transform: scale(0.2)}
  to {transform: scale(1)}
}

@keyframes kf-hover {
  100% {transform: rotate(1turn)}
}
<div class="foo">
  Hello world
</div>

【问题讨论】:

    标签: html css css-animations


    【解决方案1】:

    这可能是解决方案。您目前有两个动画完全使用属性transform,您需要做的就是将它们分开,那么问题就很简单了。我还在悬停时添加了暂停/运行状态,以增加一点流畅度。

    .foo {
      margin: auto;
      margin-top: 100px;
      padding: 1em;
      width: fit-content;
      border: solid 1px black;
      background: red;
      color: white;
      font-size: 2em;
      
      /* The infinite animation */
      animation: kf-hover 10s infinite;
      animation-play-state: paused;
    }
    
    .bar {
      /* The initial animation */
      animation: kf-initial 2s;
    }
    
    .foo:hover {
      animation-play-state: running;
    }
    
    @keyframes kf-initial {
      from {
        transform: scale(0.2)
      }
      to {
        transform: scale(1)
      }
    }
    
    @keyframes kf-hover {
      100% {
        transform: rotate(1turn)
      }
    }
    <div class="bar">
      <div class="foo">
        Hello world
      </div>
    </div>

    【讨论】:

    • 感谢您的回复,我期待这种解决方案。这有点不方便,因为我现在有 2 个 div 用于相同的内容,仅用于此目的。所以我会采用它,但让问题公开,以防有人有一些神奇的解决方案;)
    【解决方案2】:

    如果您不希望初始状态动画在鼠标离开悬停状态后再次运行,并且您希望元素返回到其先前的方向。您需要使用 JavaScript 向 foo 元素添加一个类,并为该类添加不再允许该动画运行的 CSS。

    const fooEl = document.querySelector(".foo");
    
    fooEl.addEventListener("mouseleave", () => {
      fooEl.classList.add("stopped");
    })
    .foo {
      margin: auto;
      margin-top: 100px;
      padding: 1em;
      width: fit-content;
      border: solid 1px black;
      background: red;
      color: white;
      font-size: 2em;
        
      /* The initial animation */
      animation: kf-initial 2s;
    }
    
    .stopped {
      animation: none;
    }
    
    .foo:hover {
      /* The infinite animation */
      animation: kf-hover 10s infinite;
    }
    
    @keyframes kf-initial {
      from {transform: scale(0.2)}
      to {transform: scale(1)}
    }
    
    @keyframes kf-hover {
      100% {transform: rotate(1turn)}
    }
    <div class="foo">
      Hello world
    </div>

    【讨论】:

    • 当然我怎么没看到。非常感谢你们,这是解决这个问题的 2 个不错的方法!
    • 不客气。祝你好运,继续编码!
    猜你喜欢
    • 2022-10-06
    • 1970-01-01
    • 2012-01-23
    • 2015-11-27
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 2012-07-22
    相关资源
    最近更新 更多