中文
已保存草稿
Loading & status · Vanilla JS + CSS

Stacking toast notifications

堆叠通知弹出

New toast notifications slide up into the front while older ones stack behind and expand on hover.

Also searched as: 右下角通知弹窗, 消息队列堆叠提示, Toast 通知依次弹出, 多条提醒叠放展开

AI Markdown (.md)
Placement
Card list, Footer
Mood
Crisp, Soft
Trigger
状态变化
Site types
工具和应用, 品牌官网, 个人网站

How it works & accessibility

Each notification animates in from 16px below with configurable duration and easing, older items offset and scale down via stack transforms and expand into a full list on hover or keyboard focus, an aria-live region alternates zero-width spaces so repeated messages still announce, and reduced motion skips transforms.

Best for: Card list, Footer (状态变化).

Reduced motion: 跳过滑入和叠放位移动画,新通知直接出现,关闭时直接移除;读屏仍正常提示

Mobile & touch: 通知卡片宽度自适应屏幕留白,点击关闭按钮尺寸不小于 36px,不依靠悬停才能关闭

Key parameters

ParameterKeyDefaultRangeNotes
弹出时长duration360ms——
缓动easingcubic-bezier(0.22, 1, 0.36, 1)——

Ready-to-paste AI prompt

Add “Stacking toast notifications” to the card list in my project: Each notification animates in from 16px below with configurable duration and easing, older items offset and scale down via stack transforms and expand into a full list on hover or keyboard focus, an aria-live region alternates zero-width spaces so repeated messages still announce, and reduced motion skips transforms.
Parameters: duration: 360ms, easing: cubic-bezier(0.22, 1, 0.36, 1).
Preserve existing content and layout. Respect prefers-reduced-motion by showing the final state. Content must remain visible if JavaScript fails or is disabled.
Reference: https://donglang.linter.top/effects/toast-stack.md (canonical specification and reference code).

Dependency-free reference code

CSS
/* 堆叠通知弹出(Stacking toast notifications)样式,配合 toast-stack.js。 */
.tst-stack {
  position: relative;
  width: min(320px, 100%);
  min-height: 52px;
}

.tst-live {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.tst-item {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  padding: 12px 14px;
  border-radius: 10px;
  background: var(--tst-bg, #ffffff);
  color: var(--tst-ink, #141519);
  border: 1px solid color-mix(in srgb, currentColor 14%, transparent);
  box-shadow: 0 10px 24px -12px rgb(0 0 0 / 0.35);
  transform-origin: center bottom;
  transition:
    transform var(--tst-duration, 360ms) var(--tst-easing, cubic-bezier(0.22, 1, 0.36, 1)),
    opacity var(--tst-duration, 360ms) var(--tst-easing, cubic-bezier(0.22, 1, 0.36, 1));
  will-change: transform, opacity;
}

.tst-text {
  font-size: 13px;
  line-height: 1.4;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tst-close {
  flex-shrink: 0;
  display: inline-grid;
  place-items: center;
  width: 28px;
  height: 28px;
  border: 0;
  border-radius: 6px;
  background: transparent;
  color: inherit;
  font-size: 16px;
  line-height: 1;
  opacity: 0.6;
  cursor: pointer;
}

.tst-close:hover {
  opacity: 1;
  background: color-mix(in srgb, currentColor 8%, transparent);
}

.tst-stack.tst-reduced .tst-item {
  transition: none;
}

@media (prefers-reduced-motion: reduce) {
  .tst-stack:not(.tst-force) .tst-item {
    transition: none;
  }
}
JavaScript
// 堆叠通知弹出(Stacking toast notifications)参考实现。
// 用法:const stack = toastStack(el, { duration: 360, easing: '...' });
//       stack.push('已保存草稿'); 销毁调 stack.destroy()。

export function toastStack(root, {
  duration = 360,
  easing = 'cubic-bezier(0.22, 1, 0.36, 1)',
  maxVisible = 3,
  gap = 10,
  ignoreReducedMotion = false,
  messages = { close: '关闭通知' },
} = {}) {
  if (!(root instanceof Element)) return null;

  const dur = Number(duration) || 360;
  const easeStr = String(easing);
  const reduceQuery = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;
  const isReduced = () => Boolean(reduceQuery?.matches && !ignoreReducedMotion);

  root.classList.add('tst-stack');
  if (ignoreReducedMotion) root.classList.add('tst-force');
  root.style.setProperty('--tst-duration', `${dur}ms`);
  root.style.setProperty('--tst-easing', easeStr);

  const live = document.createElement('div');
  live.className = 'tst-live';
  live.setAttribute('aria-live', 'polite');
  live.setAttribute('aria-atomic', 'true');
  root.appendChild(live);

  const items = [];
  const timers = new Map();
  let expanded = false;
  let destroyed = false;
  let alt = false;

  const announce = (text) => {
    if (destroyed) return;
    alt = !alt;
    live.textContent = text ? `${text}${alt ? '\u200b' : ''}` : '';
  };

  const layout = () => {
    if (destroyed) return;
    let expandOffset = 0;
    items.forEach((el, idx) => {
      if (idx >= maxVisible) {
        el.style.opacity = '0';
        el.style.pointerEvents = 'none';
        el.style.transform = `translateY(${-(maxVisible * gap)}px) scale(0.88)`;
        el.style.zIndex = '0';
        return;
      }
      el.style.pointerEvents = '';
      el.style.zIndex = String(maxVisible - idx);
      if (expanded) {
        el.style.opacity = '1';
        el.style.transform = `translateY(${-expandOffset}px) scale(1)`;
        expandOffset += (el.offsetHeight || 46) + 8;
      } else {
        const y = -(idx * gap);
        const s = 1 - idx * 0.05;
        el.style.opacity = String(Math.max(0.55, 1 - idx * 0.16));
        el.style.transform = `translateY(${y}px) scale(${s})`;
      }
    });
  };

  const dismiss = (el) => {
    if (destroyed) return;
    const idx = items.indexOf(el);
    if (idx === -1) return;
    const t = timers.get(el);
    if (t) { clearTimeout(t); timers.delete(el); }
    items.splice(idx, 1);
    el.remove();
    layout();
    root.dispatchEvent(new CustomEvent('toastdismiss', { bubbles: true, detail: { remaining: items.length } }));
  };

  const onEnter = () => { expanded = true; layout(); };
  const onLeave = () => { expanded = false; layout(); };
  const onFocusIn = () => { expanded = true; layout(); };
  const onFocusOut = (ev) => {
    if (!root.contains(ev.relatedTarget)) { expanded = false; layout(); }
  };

  root.addEventListener('pointerenter', onEnter);
  root.addEventListener('pointerleave', onLeave);
  root.addEventListener('focusin', onFocusIn);
  root.addEventListener('focusout', onFocusOut);

  return {
    push(text, { tone = 'info', autoClose = 0 } = {}) {
      if (destroyed) return null;
      const el = document.createElement('div');
      el.className = 'tst-item';
      el.dataset.tone = tone;
      const span = document.createElement('span');
      span.className = 'tst-text';
      span.textContent = String(text ?? '');
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'tst-close';
      btn.setAttribute('aria-label', messages.close || '关闭通知');
      btn.textContent = '×';
      btn.addEventListener('click', () => dismiss(el));
      el.append(span, btn);

      items.unshift(el);
      root.appendChild(el);
      layout();

      if (!isReduced()) {
        el.animate(
          [{ translate: '0 16px', opacity: 0 }, { translate: '0 0', opacity: 1 }],
          { duration: dur, easing: easeStr, fill: 'none' },
        );
      }

      if (autoClose > 0) {
        timers.set(el, setTimeout(() => dismiss(el), autoClose));
      }
      announce(String(text ?? ''));
      if (destroyed) return null;
      root.dispatchEvent(new CustomEvent('toastpush', { bubbles: true, detail: { count: items.length } }));
      return el;
    },
    dismiss,
    clear() {
      if (destroyed) return;
      for (const t of timers.values()) clearTimeout(t);
      timers.clear();
      while (items.length) items.pop().remove();
    },
    count() {
      return items.length;
    },
    destroy() {
      if (destroyed) return;
      destroyed = true;
      for (const t of timers.values()) clearTimeout(t);
      timers.clear();
      while (items.length) items.pop().remove();
      live.remove();
      root.removeEventListener('pointerenter', onEnter);
      root.removeEventListener('pointerleave', onLeave);
      root.removeEventListener('focusin', onFocusIn);
      root.removeEventListener('focusout', onFocusOut);
      root.classList.remove('tst-force');
      root.style.removeProperty('--tst-duration');
      root.style.removeProperty('--tst-easing');
    },
  };
}
HTML
<div class="tst-stack" id="toasts" role="region" aria-label="通知提醒"></div>

<script type="module">
  import { toastStack } from './toast-stack.js';
  const stack = toastStack(document.getElementById('toasts'));
  stack.push('已保存草稿');
  stack.push('图片已同步到云端');
</script>

More in Loading & status

Browse all 86 effects →

Shown once per release · Always available in changelog