登录按钮执行anim-hide动画后添加hidden类仍重现问题求助
问题解决:动画结束后元素重新显示的修复方案
问题根源分析
事件判断条件错误
在onComplete函数中,判断anim-hide动画结束的逻辑写错了:你直接拿事件对象event和字符串"anim-hide"做比较,这永远不会成立,导致hidden类根本没被添加到元素上。正确的做法是读取event.animationName属性来匹配动画名称。动画样式回退问题
CSS动画默认的animation-fill-mode值为none,动画结束后元素会立刻回到初始样式(比如opacity:1),哪怕后续补上hidden类,中间也会出现短暂的显示闪回。设置animation-fill-mode: forwards可以让动画结束后保持最后一帧的状态。
修改后的完整代码
JavaScript代码
const login = document.getElementById('login'); login.addEventListener('animationend', onComplete); function onComplete(event) { if (event.animationName === "anim-show") { login.addEventListener('click', onClick); } else if (event.animationName === "anim-hide") { login.classList.add("hidden"); } } function onClick() { login.style.animationName = "anim-hide"; login.removeEventListener('click', onClick); }
CSS代码
.hidden { display: none; } #login { min-width: 150px; min-height: 10px; width: fit-content; height: fit-content; padding: 10px; background-color: #466995; border-radius: 1px; border: 2px solid #ffffff; font-size: 15px; text-align: center; animation: anim-show .5s ease forwards; /* 添加forwards保持动画最后一帧 */ user-select: none; } @keyframes anim-show { from { margin-bottom: 25%; opacity: 0; } to { margin-bottom: 0%; opacity: 1; } } @keyframes anim-hide { from { margin-top: 0%; opacity: 1; } to { margin-top: 25%; opacity: 0; } }
HTML代码
<div id="login">Login To Website</div>
额外优化提示
如果希望所有动画都默认保持最后一帧状态,可以单独给#login添加animation-fill-mode: forwards;样式,不用在每个动画声明里重复写。这样不管是初始的anim-show还是点击触发的anim-hide,都会自动保留结束后的样式。
内容的提问来源于stack exchange,提问作者WDUK
相关产品推荐
相关产品推荐

