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

实现弹窗的显示隐藏动画,关键在于使用 CSS animation 控制元素从“不可见”到“可见”的过渡过程,以及反向隐藏。下面是一个简单实用的实现方式。
先定义一个弹窗的基本 HTML 结构和默认隐藏状态:
<div class="modal" id="myModal">对应的 CSS 设置初始隐藏,并居中布局:
.modal {.modal.show {
display: flex; / 触发动画时显示 /
}
.modal-content {
width: 300px;
padding: 20px;
background: white;
border-radius: 8px;
text-align: center;
}
通过 @keyframes 定义进入动画:从透明、缩小状态逐渐变为不透明、正常大小。
立即学习“前端免费学习笔记(深入)”;
@keyframes fadeInUp {@keyframes fadeOutDown {
from {
opacity: 1;
transform: scale(1);
}
to {
opacity: 0;
transform: scale(0.8);
}
}
将动画应用到弹窗内容上:
.modal.show .modal-content {如果想在关闭时也播放动画,不能直接用 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() 即可实现平滑隐藏。
可以使用 animationend 事件代替 setTimeout,更精确地控制流程:
content.addEventListener('animationend', function handler(e) {基本上就这些。利用 keyframes 定义动画,结合 JS 控制类名和 display,就能做出流畅的弹窗动效。关键是注意 display 和 animation 的配合时机,避免动画未执行就被隐藏。
以上就是如何通过css animation实现弹窗显示隐藏动画的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号