如何实现Popup滑出动画?已有滑入动画但滑出功能失效
问题分析
你当前的弹窗滑出动画不生效,核心原因是关闭弹窗时直接设置了display: none——元素瞬间被隐藏,CSS动画根本没有执行的时间。
解决方案
我们需要先触发滑出动画,等动画执行完成后再隐藏弹窗,具体修改如下:
1. 添加滑出动画的CSS代码
在现有CSS中新增滑出动画和对应的类:
/* 新增滑出动画 */ @keyframes popOutAnimation { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(0); } } /* 滑出动画类 */ .popup-content.pop-out { animation: popOutAnimation 1s forwards; }
2. 修改JavaScript函数
调整openPopup和closePopup函数,确保动画正确触发:
function openPopup() { const popup = document.getElementById("popup"); const popupContent = popup.querySelector(".popup-content"); // 移除滑出类,重置动画状态 popupContent.classList.remove("pop-out"); // 先显示弹窗,再触发重绘(确保动画生效) popup.style.display = "flex"; void popupContent.offsetWidth; // 强制重绘 } function closePopup() { const popup = document.getElementById("popup"); const popupContent = popup.querySelector(".popup-content"); // 添加滑出动画类 popupContent.classList.add("pop-out"); // 监听动画结束事件,完成后隐藏弹窗 popupContent.addEventListener("animationend", function handler() { popup.style.display = "none"; // 移除事件监听,避免重复触发 popupContent.removeEventListener("animationend", handler); // 移除滑出类,方便下次打开 popupContent.classList.remove("pop-out"); }); }
3. 调整弹窗容器的CSS
原.popup没有设置display: flex,打开时需要设置才能让内容居中,修改.popup的CSS:
.popup { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); align-items: center; justify-content: center; z-index: 9999; }
4. 修正HTML中的按钮语法错误
原HTML里的按钮有多余的引号,修正:
<div class="popup-buttons"> <div> <button onclick="window.location.href='#'">General Websites</button> </div> <div> <button onclick="window.location.href='#'">Fivem Websites</button> </div> <div> <button onclick="window.location.href='#'">Custom made websites</button> </div> <div> <button onclick="window.location.href='#'">Ecommerce Websites</button> </div> <div> <button onclick="window.location.href='#'">All Websites</button> </div> </div>
原理说明
- 关闭弹窗时,先给内容添加滑出动画类,让动画完整执行
- 通过
animationend事件监听动画结束,此时再设置display: none隐藏弹窗 - 打开弹窗时强制重绘,确保滑入动画能重新触发,避免因为DOM状态缓存导致动画不生效
内容的提问来源于stack exchange,提问作者Moon Boy
相关产品推荐
相关产品推荐

