You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中调用CSS关键帧动画?心形图标点击动画失效问题

心形图标点击动画与计数问题修复

问题根源

  • CSS关键帧存在语法错误:transform: translateY(0px;);里多了个多余分号,会导致动画解析异常
  • JS变量冲突:用const count获取计数DOM元素后,又直接给count赋值0,这会覆盖DOM引用,属于语法错误(你说计数正常大概率是实际代码里的笔误)
  • 动画仅触发一次:添加animation类后未移除,CSS动画默认只执行一次,再次点击时类已存在,浏览器不会重新触发动画

修复方案

  1. 修正CSS关键帧里的语法错误,去掉translateY(0px;)中的多余分号
  2. 单独声明计数变量,避免覆盖DOM元素引用
  3. 通过移除再添加类的方式,结合强制重绘确保每次点击都能触发动画,同时监听动画结束事件重置类

修正后的完整代码

HTML

<div class="center">
  <i class="fa-regular fa-heart" onclick="heartAnimation()"></i>
  <p id="count">0</p>
</div>

CSS

@keyframes heart {
  40% {
    transform: translateY(-10px);
    color: red;
  }
  95% {
    transform: translateY(0px);
    color: red;
  }
  100% {
    color: black;
  }
}

.animation {
  animation: heart 1s;
}

JavaScript

const icon = document.querySelector(".fa-regular");
const countEl = document.querySelector("#count");
let clickCount = 0;

function heartAnimation() {
  // 先移除类再添加,强制触发动画
  icon.classList.remove("animation");
  // 强制浏览器重绘,避免移除后立即添加不生效
  void icon.offsetWidth;
  icon.classList.add("animation");
  
  clickCount++;
  countEl.innerText = clickCount;
}

// 动画结束后自动移除类,保障下次点击正常触发
icon.addEventListener("animationend", () => {
  icon.classList.remove("animation");
});

内容的提问来源于stack exchange,提问作者FroggyGroggy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 05:51:15