JS 特效 词条目录
前端Wiki/JS 特效/滚动与组件/常用组件

Toast 提示条

Toast 提示:操作后顶部/底部滑出一条轻提示(“已保存”“网络错误”),几秒后自动消失。组件逻辑:创建元素 → 插入容器 → 加 .show → 定时移除。用函数式调用最顺手。

设计要点:同时多条不重叠(堆叠排列)、悬停暂停倒计时、加 type 区分成功/失败/警告、淡出动画后 remove 避免堆积。

  • 弹出:appendChild + requestAnimationFrame 触发 transition
  • setTimeout 自动移除;移除前先收再删(淡出动画)
  • 类型区分:success/error/warning 换色与图标
HTML
<style>
#tBox { position: fixed; top: 16px; left: 50%; transform: translateX(-50%);
        z-index: 100; display: flex; flex-direction: column; gap: 8px; }
.toast { padding: 10px 20px; border-radius: 10px; color: #fff; font-size: 14px;
         box-shadow: 0 8px 24px rgba(0,0,0,.2);
         opacity: 0; transform: translateY(-16px); transition: .3s ease; }
.toast.show { opacity: 1; transform: none; }
.toast.ok { background: #57ab5a; } .toast.err { background: #e5534b; }
.toast.info { background: #4a9eff; }
#tBar { text-align: center; margin-top: 12px; }
#tBar button { padding: 8px 16px; margin: 0 6px; border: none; border-radius: 8px;
               background: #f0e6ff; cursor: pointer; }
</style>
<div id="tBar">
  <button onclick="toast('保存成功', 'ok')">成功提示</button>
  <button onclick="toast('保存失败,请重试', 'err')">失败提示</button>
  <button onclick="toast('这是一条普通消息', 'info')">普通提示</button>
</div>
<div id="tBox"></div>
<script>
function toast(msg, type) {
  var box = document.getElementById('tBox');
  var el = document.createElement('div');
  el.className = 'toast ' + (type || 'info');
  el.textContent = msg;
  box.appendChild(el);
  requestAnimationFrame(function () { el.classList.add('show'); });
  setTimeout(function () {
    el.classList.remove('show');
    setTimeout(function () { el.remove(); }, 300);   // 等淡出动画
  }, 2400);
}
</script>
本节要点Toast = 动态创建 + RAF 触发进入 + 定时淡出移除;多类型与堆叠是完整形态。
🔗 相关词条DOM事件CSS 特效