You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在鼠标移出后重复CSS圆形动画并从暂停处继续

实现鼠标移出后从暂停位置重复执行CSS圆形动画

我来帮你搞定这个需求!要实现鼠标悬停时暂停动画,移出后从暂停位置继续重复执行圆形描边动画,我们可以结合CSS动画状态控制和描边属性来实现。下面是完整的可运行代码和关键细节说明:

完整HTML代码

<section class="container">
  <figure class="chart" data-percent="100">
    <figcaption>HTML</figcaption>
    <svg width="200" height="200">
      <circle class="outer" cx="95" cy="95" r="85" transform="rotate(-90, 95, 95)"/>
    </svg>
  </figure>
</section>

完整CSS代码

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.chart {
  position: relative;
}

.chart figcaption {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 1.2rem;
  font-weight: bold;
}

.outer {
  fill: transparent;
  stroke: #333;
  stroke-width: 10;
  /* 计算圆形周长:2 * π * r = 2 * 3.14 * 85 ≈ 533.8 */
  stroke-dasharray: 533.8;
  stroke-dashoffset: 533.8;
  /* 定义动画:从初始偏移量到0,无限循环,线性速度 */
  animation: circleStroke 3s linear infinite;
}

/* 鼠标悬停时暂停动画 */
.chart:hover .outer {
  animation-play-state: paused;
}

/* 描边动画关键帧 */
@keyframes circleStroke {
  to {
    stroke-dashoffset: 0;
  }
}

关键细节说明

  • 动画暂停与恢复:核心是用animation-play-state属性——hover时设为paused让动画停在当前帧,鼠标移出后自动恢复为running,动画会从暂停的位置继续执行,而不是从头开始。
  • 描边动画原理:通过stroke-dasharray设置描边的虚线长度(等于圆形周长),stroke-dashoffset控制虚线的偏移量,动画中逐渐将偏移量从周长值降到0,就实现了圆形描边的效果。
  • 无限重复animation-iteration-count: infinite确保动画会循环执行,移出鼠标后从暂停点继续循环。

如果需要适配不同的百分比(比如data-percent不是100),可以用CSS变量结合calc()动态计算stroke-dashoffset,不过当前你的需求用上面的代码就完全满足啦!

内容的提问来源于stack exchange,提问作者web-stars

火山引擎 最新活动