使用Animista的CSS弹窗动画无法居中问题求助
问题原因
- 核心问题是
transform属性被动画覆盖:你给#popup设置的transform: translate(-50%, -50%)是实现居中的关键,但动画规则里的transform只定义了Z轴变换,执行动画时会直接覆盖原有transform值,导致居中失效。 - 次要问题1:重复ID错误,你遍历所有非弹窗元素统一设置
id="blur",但HTML中ID是唯一值,多个元素共用同一个ID会导致选择器异常。 - 次要问题2:退场动画结束后弹窗未隐藏,动画结束后弹窗仅透明,依然占据文档位置会遮挡下方元素点击,且关闭按钮是a标签,未阻止默认跳转行为会导致点击后页首跳动。
- 次要问题3:body未指定最小高度,若页面内容较少时body高度不足,垂直居中的参照基准会异常。
修复方案
1. 修正CSS部分
* { margin: 0; padding: 0; box-sizing: border-box; } body { position: relative; min-height: 100vh; /* 新增:保证body高度占满视口,垂直居中正常生效 */ } /* 把原有的#blur.active改为类选择器,适配多元素模糊 */ .blur.active { filter: blur(10px); pointer-events: none; user-select: none; } a { position: relative; padding: 5px 20px; display: inline-block; margin-top: 20px; text-decoration: none; color: #fff; background: #111; } #popup { position: absolute; top: 50%; left: 50%; transform: translate( -50%, -50%); padding: 50px; box-shadow: 0 5px 30px rgba(0, 0, 0, .30); width: 600px; background: #fff; display: none; } .slide-in-fwd-center { animation: slide-in-fwd-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both; } /* 关键帧新增translate(-50%, -50%),保留居中属性 */ @keyframes slide-in-fwd-center { 0% { transform: translate(-50%, -50%) translateZ(-1400px); opacity: 0; } 100% { transform: translate(-50%, -50%) translateZ(0); opacity: 1; } } .slide-out-fwd-center { animation: slide-out-fwd-center 0.7s cubic-bezier(0.550, 0.085, 0.680, 0.530) both; } /* 关键帧新增translate(-50%, -50%),保留居中属性 */ @keyframes slide-out-fwd-center { 0% { transform: translate(-50%, -50%) translateZ(1); opacity: 1; } 100% { transform: translate(-50%, -50%) translateZ(600px); opacity: 0; } }
2. 修正JS部分
const allEl = document.querySelectorAll('body > *:not(#popup):not(script)'); const closeBtn = document.querySelector('#popup-close-btn'); const popup = document.querySelector('#popup'); allEl.forEach(el => { el.classList.add('blur'); // 改为添加类,而非设置重复ID }); const blurEls = document.querySelectorAll('.blur'); // 选中所有需要模糊的元素 setTimeout(() => { blurEls.forEach(el => el.classList.add('active')); popup.style.display = "block"; popup.classList.add('slide-in-fwd-center'); popup.classList.remove('slide-out-fwd-center'); }, 2000); closeBtn.addEventListener('click', (e) => { e.preventDefault(); // 阻止a标签默认跳转 blurEls.forEach(el => el.classList.remove('active')); popup.classList.add('slide-out-fwd-center'); popup.classList.remove('slide-in-fwd-center'); // 监听动画结束后隐藏弹窗,避免遮挡内容 popup.addEventListener('animationend', () => { if(popup.classList.contains('slide-out-fwd-center')) { popup.style.display = "none"; } }, {once: true}); // 单次监听,避免重复绑定事件 });
内容的提问来源于stack exchange,提问作者s.khan
相关产品推荐
相关产品推荐

