点击email_nav类DIV实现错误提示淡入淡出及定时隐藏,求代码优化
优化ARG网站后端断开错误提示动画方案
优化后的实现代码
HTML 结构
<div class="email_nav"> <button class="email-btn">Reply</button> <button class="email-btn">Reply All</button> <button class="email-btn">Forward</button> <button class="email-btn">Delete</button> </div> <!-- 错误提示框,默认隐藏 --> <div class="error-alert" role="alert" aria-hidden="true"> 后端连接已断开,无法执行此操作 </div>
CSS 样式(故障闪烁+淡出动画)
/* 错误提示框基础样式 */ .error-alert { position: fixed; top: 20px; right: 20px; padding: 12px 24px; background: #111; color: #fff; border: 2px solid #ff4444; border-radius: 4px; font-family: monospace; /* 复古终端字体增强ARG氛围 */ opacity: 0; pointer-events: none; transition: opacity 0.3s ease; } /* 闪烁+淡出动画关键帧 */ @keyframes disconnect-flicker { 0% { background: #ff4444; color: #fff; opacity: 1; } 20% { background: #fff; color: #ff4444; } 40% { background: #ff4444; color: #fff; } 60% { background: #fff; color: #ff4444; } 80% { background: #ff4444; color: #fff; } 100% { background: #111; color: #fff; opacity: 0; } } /* 触发动画的类 */ .error-alert.active { animation: disconnect-flicker 2s forwards; pointer-events: auto; aria-hidden: false; }
JavaScript 逻辑(仅负责触发动画)
// 获取元素 const emailBtns = document.querySelectorAll('.email_nav .email-btn'); const errorAlert = document.querySelector('.error-alert'); // 绑定点击事件 emailBtns.forEach(btn => { btn.addEventListener('click', () => { // 先重置动画状态,确保重复点击能重新触发 errorAlert.classList.remove('active'); void errorAlert.offsetWidth; // 强制浏览器重绘,重置动画 errorAlert.classList.add('active'); // 动画结束后重置ARIA状态 errorAlert.addEventListener('animationend', () => { errorAlert.setAttribute('aria-hidden', 'true'); }, { once: true }); }); });
优化说明
- 性能优化:用CSS关键帧动画替代JS逐帧修改样式,减少重绘重排,动画更流畅,同时降低JS逻辑复杂度。
- 状态可控:通过添加/移除
.active类触发动画,结合animationend事件自动重置状态,支持重复点击触发。 - ARG氛围强化:使用等宽字体、复古配色,贴合“后端断开的快照页面”的视觉调性。
- 无障碍支持:添加
role="alert"和aria-hidden属性,确保屏幕阅读器能正确识别提示信息。 - 代码解耦:视觉效果(CSS)与交互逻辑(JS)完全分离,后续修改动画效果无需改动JS代码。
内容的提问来源于stack exchange,提问作者Adam Tourgeman
相关产品推荐
相关产品推荐

