答案是通过CSS动画与JS交互实现弹窗显隐效果:先用display控制显示,再通过keyframes定义淡入放大(fadeInUp)和淡出缩小(fadeOutDown)动画,JS添加类名触发动画,监听animationend事件或使用setTimeout在动画结束后隐藏元素,确保动画流畅执行。

实现弹窗的显示隐藏动画,关键在于使用 CSS animation 控制元素从“不可见”到“可见”的过渡过程,以及反向隐藏。下面是一个简单实用的实现方式。
1. 弹窗结构与基础样式
先定义一个弹窗的基本 HTML 结构和默认隐藏状态:
对应的 CSS 设置初始隐藏,并居中布局:
.modal {display: none; /* 默认不显示 */
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
background-color: rgba(0,0,0,0.5);
justify-content: center;
align-items: center;
}
.modal.show {
display: flex; / 触发动画时显示 /
}
.modal-content {
width: 300px;
padding: 20px;
background: white;
border-radius: 8px;
text-align: center;
}
2. 添加淡入放大动画
通过 @keyframes 定义进入动画:从透明、缩小状态逐渐变为不透明、正常大小。
立即学习“前端免费学习笔记(深入)”;
@keyframes fadeInUp {from {
opacity: 0;
transform: scale(0.8);
}
to {
opacity: 1;
transform: scale(1);
}
}
@keyframes fadeOutDown {
from {
opacity: 1;
transform: scale(1);
}
to {
opacity: 0;
transform: scale(0.8);
}
}
将动画应用到弹窗内容上:
.modal.show .modal-content {animation: fadeInUp 0.3s ease forwards;
}
3. 隐藏时播放退出动画
如果想在关闭时也播放动画,不能直接用 display: none。需要监听动画结束事件来真正隐藏元素。
JavaScript 示例:
const modal = document.getElementById('myModal');// 打开弹窗
function openModal() {
modal.classList.add('show');
modal.style.display = 'flex'; // 先设为 flex 触发渲染
}
// 关闭弹窗
function closeModal() {
const content = modal.querySelector('.modal-content');
content.style.animation = 'fadeOutDown 0.3s ease forwards';
setTimeout(() => {
modal.classList.remove('show');
modal.style.display = 'none';
content.style.animation = ''; // 重置动画
}, 300); // 动画时长匹配
}
点击遮罩或按钮调用 closeModal() 即可实现平滑隐藏。
4. 可选:更优雅的动画控制
可以使用 animationend 事件代替 setTimeout,更精确地控制流程:
content.addEventListener('animationend', function handler(e) {if (e.animationName === 'fadeOutDown') {
modal.classList.remove('show');
modal.style.display = 'none';
content.removeEventListener('animationend', handler);
}
});
基本上就这些。利用 keyframes 定义动画,结合 JS 控制类名和 display,就能做出流畅的弹窗动效。关键是注意 display 和 animation 的配合时机,避免动画未执行就被隐藏。










