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

文本显示/隐藏动画异常求助:隐藏无动画效果

问题出在你直接用display: none隐藏元素——这会让元素瞬间消失,CSS动画根本没机会运行。另外显示逻辑也没正确触发动画,现在的text-fade-in类是默认加上的,第一次显示时不会重新触发动画。

下面是修复方案:

1. 重构CSS样式

把元素的初始状态和动画类分离,确保动画只在触发时生效:

p {
  text-align: center;
}

/* 文本元素的初始状态 */
.text-item {
  opacity: 0;
  transform: translateX(-10vw);
  display: none;
}

@keyframes text-fade-in {
  0% {
    opacity: 0;
    transform: translateX(-10vw);
  }
  80% {
    opacity: 1;
  }
  100% {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 显示动画类 */
.text-fade-in {
  animation: text-fade-in 0.4s easeOutCirc 0.4s forwards;
}

@keyframes text-fade-out {
  0% {
    opacity: 1;
    transform: translateX(0);
  }
  80% {
    opacity: 0;
  }
  100% {
    opacity: 0;
    transform: translateX(-10vw);
  }
}

/* 隐藏动画类 */
.text-fade-out {
  animation: text-fade-out 0.4s easeOutCirc forwards;
}

2. 修改JS逻辑

核心是先触发动画,等动画结束后再设置display:none,同时处理类的添加/移除避免冲突:

function hide(id) {
  const elem = document.getElementById(id);
  // 先确保元素是显示状态,才能触发动画
  elem.style.display = 'block';
  // 添加隐藏动画类,移除显示动画类
  elem.classList.add('text-fade-out');
  elem.classList.remove('text-fade-in');
  
  // 监听动画结束事件,完成后隐藏元素
  elem.addEventListener('animationend', function handler() {
    elem.style.display = 'none';
    elem.classList.remove('text-fade-out');
    // 移除事件监听,避免重复触发
    elem.removeEventListener('animationend', handler);
  });
}

function show(id) {
  const elem = document.getElementById(id);
  // 先显示元素
  elem.style.display = 'block';
  // 添加显示动画类,移除隐藏动画类
  elem.classList.add('text-fade-in');
  elem.classList.remove('text-fade-out');
}

3. 调整HTML结构

把文本元素的class改成统一的text-item,去掉内联的display:none(由CSS控制):

<button onclick="show('Text1'); hide('Text2'); hide('Text3')">Text1</button>
<button onclick="show('Text2'); hide('Text1'); hide('Text3')">Text2</button>
<button onclick="show('Text3'); hide('Text1'); hide('Text2')">Text3</button>
<button onclick="hide('Text1'); hide('Text2'); hide('Text3')">Hide</button>

<p class="text-item" id="Text1">Text1</p>
<p class="text-item" id="Text2">Text2</p>
<p class="text-item" id="Text3">Text3</p>

关键说明

  • 不能直接用display:none中断动画:元素一旦设为display:none,浏览器会直接终止它的所有动画,所以必须等动画完成后再设置。
  • 动画类要互斥:显示时移除隐藏类,隐藏时移除显示类,避免动画冲突。
  • 移除animationend监听:防止同一元素多次触发隐藏时,事件监听叠加导致错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:23:31