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

移动端按钮点击后保持focus/active状态致CSS动画无法重复触发

解决移动端按钮点击无法重复触发CSS动画的问题

问题原因

移动端触摸交互中,按钮被点击后会持续保持focus状态,原代码依赖:hover伪类触发动画——但触摸设备上:hover仅在第一次触摸时触发,后续触摸不会重新触发该伪类,导致必须点击空白区域让按钮失焦后,才能再次触发动画。

解决方案

通过JavaScript监听点击事件,用自定义类替代:hover伪类触发动画,确保每次点击都能强制重新执行动画。

修改后的代码

CSS 部分

.btn_container {
  color: #35f8ff;
  position: relative;
  display: inline-block;
  text-align: center;
  margin: 2.5rem auto;
}

.prog_btn {
  text-transform: uppercase;
  font-size: 1.3rem;
  padding: 10px 25px;
  z-index: 3;
  background-color: transparent;
  cursor: pointer;
  transition: 0.2s ease-out;
  position: relative;
  margin: auto;
}

.btn_container .svgStroke {
  position: absolute;
  z-index: 1;
  width: 100%;
  top: -25%;
  left: 0;
}

.btn_container .svgStroke path {
  stroke-dasharray: 100;
  stroke-dashoffset: -800;
  stroke-width: 2;
  transition: all 1s ease-in-out;
  stroke: #35f8ff;
}

@keyframes dash {
  0% {
    stroke-dasharray: 100;
    stroke-width: 2;
  }
  50% {
    stroke-width: 4;
    stroke: #35f8ff;
    filter: drop-shadow(0px 0px 3px #e8615a) drop-shadow(0px 0px 20px #35f8ff) drop-shadow(0px 0px 150px #35f8ff);
  }
  100% {
    stroke-dashoffset: 800;
    stroke-width: 2;
  }
}

/* 用自定义active类替代hover触发动画 */
.prog_btn.active + .svgStroke path {
  cursor: pointer;
  animation: dash 1.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

/* 保留hover效果,同时添加active状态的字体变化 */
.prog_btn:hover, .prog_btn.active {
  font-size: 1.2rem;
}

.add {
  display: inline-block;
  margin-right: 0.75rem;
  height: 1.5rem;
  width: 1.5rem;
}

HTML 部分(原结构无需修改)

<div class="btn_container">
  <div class="prog_btn">
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="add">
      <path
        stroke-linecap="round"
        stroke-linejoin="round"
        d="M12 4.5v15m7.5-7.5h-15"
      ></path>
    </svg> Add 10%
  </div>
  <svg class="svgStroke" width="222" height="65" viewBox="0 0 222 85" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path
      d="M205 84H21L1 63.4941V18.5765L21 1H205L221 18.5765V63.4941L205 84Z"
      stroke="white"
      stroke-width="2"
    ></path>
  </svg>
</div>

JavaScript 部分

const progBtn = document.querySelector('.prog_btn');
const svgPath = document.querySelector('.svgStroke path');

// 点击按钮时添加active类触发动画
progBtn.addEventListener('click', () => {
  progBtn.classList.add('active');
});

// 动画结束后移除active类,确保下次点击可重新触发
svgPath.addEventListener('animationend', () => {
  progBtn.classList.remove('active');
});

原理说明

  1. 用自定义.active类替代:hover伪类触发动画,避开移动端触摸状态残留的问题。
  2. 点击按钮时添加类触发动画,动画结束后自动移除类,保证每次点击都能重新触发动画逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:20:23