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

如何实现点击按钮后CSS动画持续激活3秒的效果

当前使用:active伪类触发动画仅在按钮按住时生效,松开后动画立即中断,需通过JS控制类名实现点击后持续3秒的效果,修改方案如下:


第一步:修改CSS代码

把布局属性移到基础类避免样式跳动,单独设置动画触发类:

.catcoinZ {
  background: none;
  border: none;
  /* 布局属性移到基础类 */
  perspective: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 25vh;
}

/* 单独的动画触发类 */
.catcoinZ.coin-rotating {
  transform: rotateY(45deg);
  /* 3秒线性播放,结束后保持最后一帧状态 */
  animation: rotateAnimation 3s linear forwards;
}

@keyframes rotateAnimation {
  from {
    transform: rotateY(45deg);
  }
  to {
    transform: rotateY(225deg);
  }
}

第二步:修改JavaScript代码

点击时添加动画类,3秒后自动移除,同时兼容连续点击重新触发动画的需求:

function coinflip() {
  const btn = document.querySelector('.catcoinZ');
  const img = document.getElementById("coinimage");
  // 先移除类+触发重排,实现连续点击可重新播放动画
  btn.classList.remove('coin-rotating');
  void btn.offsetWidth;
  btn.classList.add('coin-rotating');

  // 3秒后移除动画类,方便下次点击触发
  setTimeout(() => {
    btn.classList.remove('coin-rotating');
  }, 3000);

  // 原有抛硬币逻辑保留
  const coinside = Math.random();
  if (coinside <= 0.5) {
    img.src = "CatCoingood.png";
  } else {
    img.src = "CatCoinbad.png";
  }
}

第三步:HTML代码无需调整

原有HTML结构可直接正常使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:45:05