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

如何用Animate.css实现点击按钮后元素淡出并解决直接淡出问题

解决Animate.css进/出动画类冲突问题

问题核心是Animate.css的多个动画类会同时触发,初始不能同时添加animate__fadeInUp和animate__fadeOutUp,得通过JavaScript控制动画切换时机:

步骤1:调整初始HTML结构

初始只保留进入动画的类,不要加退出动画类:

<div class="animate__animated animate__fadeInUp animate__fast" role="alert" id="alertElement">
  <strong>${alertmsg}</strong> ${msg}
  <button type="button" class="btn-close" aria-label="Close" id="closeBtn"></button>
</div>

步骤2:用JavaScript控制动画切换

给关闭按钮绑定点击事件,先移除进入动画类,再添加退出动画类,最后在动画结束后处理元素:

const alertEl = document.getElementById('alertElement');
const closeBtn = document.getElementById('closeBtn');

closeBtn.addEventListener('click', () => {
  // 移除进入动画类,避免和退出动画冲突
  alertEl.classList.remove('animate__fadeInUp');
  // 添加退出动画类,触发淡出效果
  alertEl.classList.add('animate__fadeOutUp');

  // 监听动画结束事件,完成后隐藏/移除元素
  const handleEnd = () => {
    alertEl.style.display = 'none';
    // 移除监听,防止重复触发
    alertEl.removeEventListener('animationend', handleEnd);
  };
  alertEl.addEventListener('animationend', handleEnd);
});

原理说明

Animate.css的动画基于CSS @keyframes实现,同一个元素上同时存在多个动画类时,浏览器会同时执行所有动画,导致你看到的"直接淡出"问题。通过先移除进入动画类,再添加退出动画类,能确保动画按顺序执行:先完成进入动画,点击后触发退出动画。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:49:54