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

模态框关闭时CSS动画时序问题:如何实现开合百叶窗效果?

解决模态框关闭时百叶窗动画不生效的问题

核心问题是动画还没执行完就直接设置display: hidden中断了动画流程,必须等关闭动画完全结束后再隐藏模态框。下面是具体实现方案:

1. 完善CSS动画定义

先定义打开和关闭的双向百叶窗动画,以及对应的类:

/* 模态框容器默认隐藏 */
.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
}

/* 百叶窗打开动画 */
@keyframes blind-in {
  0% {
    clip-path: inset(100% 0 0 0);
  }
  100% {
    clip-path: inset(0 0 0 0);
  }
}

/* 百叶窗关闭动画 */
@keyframes blind-out {
  0% {
    clip-path: inset(0 0 0 0);
  }
  100% {
    clip-path: inset(100% 0 0 0);
  }
}

/* 打开动画触发类 */
.blind-content.in {
  animation: blind-in 0.5s forwards;
}

/* 关闭动画触发类 */
.blind-content.out {
  animation: blind-out 0.5s forwards;
}

.modal-content {
  position: relative;
  margin: 10% auto;
  width: 80%;
  background: white;
  padding: 20px;
}

.modal-close {
  float: right;
  cursor: pointer;
  width: 20px;
  height: 20px;
  background: #ccc;
}

2. 修改JavaScript逻辑

通过监听动画结束事件控制模态框的显示/隐藏,避免提前中断动画:

const modal = document.getElementById('modal-one');
const modalContent = modal.querySelector('.modal-content');
const closeBtn = modal.querySelector('.modal-close');
const openBtn = document.querySelector('.modal-open'); // 假设你有触发打开的按钮

// 打开模态框逻辑
openBtn.addEventListener('click', () => {
  modal.style.display = 'block';
  // 重置类状态,确保每次打开都能触发动画
  modalContent.classList.remove('out');
  modalContent.classList.add('in');
});

// 关闭模态框逻辑
closeBtn.addEventListener('click', () => {
  modalContent.classList.remove('in');
  modalContent.classList.add('out');
  
  // 监听动画结束,完成后再隐藏模态框
  const handleAnimationEnd = () => {
    modal.style.display = 'none';
    modalContent.removeEventListener('animationend', handleAnimationEnd);
    // 移除关闭类,避免影响下次打开
    modalContent.classList.remove('out');
  };
  
  modalContent.addEventListener('animationend', handleAnimationEnd);
});

关键逻辑说明

  • 打开时:先显示模态框容器,再添加打开动画类,确保动画能正常触发。
  • 关闭时:先切换到关闭动画类,等animationend事件触发(动画完全结束)后,再设置模态框为display: none,同时移除事件监听防止重复触发。
  • 每次动画切换前移除对立的类,避免类冲突导致动画异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:30:48