中文
海边的周末
城市夜跑
Page & layout · Vanilla JS + CSS

Crossfade

原地交叉淡化

Swap content in place by fading the new one over the old.

Also searched as: 换图时新旧两张在原地一出一进, 图片原地淡入淡出切换, 轮播图淡入淡出换图, 两张图叠在一起慢慢换

AI Markdown (.md)
Placement
Image, Page transition
Mood
Soft, Refined
Trigger
点击
Site types
个人网站, 作品集, 博客

How it works & accessibility

Stack the slides in one grid cell, keep hidden slides inert and aria-hidden, fade the incoming slide in on top while the outgoing one stays opaque, then hide it; a new switch mid-fade commits the previous one, and reduced motion swaps instantly.

Best for: Image, Page transition (点击).

Reduced motion: 不淡入,直接换成新的一张;事件照发

Mobile & touch: 和桌面一样;手机上图大,时长可以短一点(300ms 左右)

Key parameters

ParameterKeyDefaultRangeNotes
时长duration500ms——
缓动easingcubic-bezier(0.4, 0, 0.2, 1)——

Ready-to-paste AI prompt

Add “Crossfade” to the image in my project: Stack the slides in one grid cell, keep hidden slides inert and aria-hidden, fade the incoming slide in on top while the outgoing one stays opaque, then hide it; a new switch mid-fade commits the previous one, and reduced motion swaps instantly.
Parameters: duration: 500ms, easing: cubic-bezier(0.4, 0, 0.2, 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/crossfade.md (canonical specification and reference code).

Dependency-free reference code

CSS
/* 原地交叉淡化的样式,配合 crossfade.js。脚本装好以后(容器带 data-cf-ready)几张叠在同一个 grid 格子里,高度取最高的那张,不用 position: absolute;
   没有脚本时几张按正常顺序竖着排,内容都看得见。藏起来、淡入、谁在上面都由脚本写在每张的行内样式上。 */
[data-cf-ready] {
  display: grid;
}
[data-cf-ready] > * {
  grid-area: 1 / 1;
}
JavaScript
// 原地交叉淡化(Crossfade)· 原生 JS,不依赖任何库。
// 参考 StyleKit 的 crossfade、Animation Handbook 的 crossfade、Motion Lexicon 的 crossfade 的做法(都是 MIT),自己实现,没有复制代码。
// 用法:crossfade(容器),容器的每个子元素是一张"幻灯片"(配合 crossfade.css)。返回 { show(index), next(), prev(), index, destroy() }。
// 装上以后给容器加 data-cf-ready:CSS 把几张叠在同一个 grid 格子里(高度取最高的那张,不用 position: absolute)。
// 当前那张(开始是第一张,或者带 data-current 的那张)看得见;别的 opacity: 0、visibility: hidden,加 inert 和 aria-hidden(里面的链接、按钮 Tab 不到、读屏读不到)。
// 切换用的按钮放在容器外面(放在幻灯片里面的话,那张被藏起来时按钮跟着变成 inert,焦点会丢)。
// 焦点在要藏起来的那张里时,藏起来以后焦点会回到页面开头(浏览器处理 inert 的方式),脚本不替你挪;要自动切换的轮播,记得焦点在里面时先停一停。
// show(i):越界或就是当前,什么都不做、返回 false。新的一张变成看得见、加 class="is-entering"、放在旧的上面(z-index: 1),用 element.animate 从透明淡入;
// 旧的一直不透明不动(先不淡出:两张都半透明时底色会透出来,中间一下变暗),淡完才把旧的藏起来,新的成为当前,最后在容器上发
// CustomEvent('crossfade', { detail: { from, to } })(下标从 0 起;样式清好、状态还好以后再发)。返回 true。
// 上一次淡入还没走完又来一次:先把上一次提交(立刻到终点、发事件),再开始新的,不丢。页面上的动画被外部全部取消时也当成走完了,提交。
// 提交时发的事件里页面又切了一次(回调里调 show、next、prev):以回调里那一次为准,外面这次什么都不做、返回 false;回调里 destroy() 了也返回 false。
// 减少动态时没有淡入,提交是同步的,这条规则一样适用:回调里 destroy() 或又切了别的,外面这次返回 false。
// next()、prev():循环切换,返回值和 show 一样。选项:duration 毫秒、easing CSS 缓动,和数据里一样。
// 两张一样大、不透明时最好看(有透明区域的内容,淡入过程中会透出下面那张)。
// 幻灯片上网站自己写的 transition(比如 opacity、all)不用去掉:脚本改样式(藏起来、放到上面、还原)的那一下会先关掉它们——
// 写好样式、强制回流、再还原,不然"藏起来"会变成一段慢慢的淡出、还原时会淡入一截。淡入本身用的是 element.animate,别再给幻灯片写 opacity 的动画去和它抢。
// 开启"减少动态"时不淡,直接换(照样提交、发事件);ignoreReducedMotion 只给演示强制播放用。
// 只认容器里的 HTML 元素当幻灯片(SVG 元素、文字节点不算);装上以后新加进容器的子元素不归它管。
// 没有脚本时几张按正常顺序竖着排,内容都看得见。destroy():取消还在播的淡入(不提交、不发事件),拿掉 data-cf-ready,原样恢复每张的 inert、aria-hidden、行内样式、class,
// 回到没有脚本时的样子;之后 show()、next()、prev() 返回 false、不改页面(index 还是最后一次的下标);对同一个容器重复调用 crossfade(),先 destroy 旧的。

// 每个容器现在装着的控制对象(对同一个容器重复调用时先拆旧的)
const prevs = new WeakMap();

export function crossfade(stack, {
  duration = 500,
  easing = 'cubic-bezier(0.4, 0, 0.2, 1)',
  ignoreReducedMotion = false,
} = {}) {
  prevs.get(stack)?.destroy();
  const reduce = !ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches;
  const slides = [...stack.children].filter((el) => el instanceof HTMLElement);
  // 装之前每张的样子(destroy() 原样还原:行内样式、inert、aria-hidden、class 属性的原文)
  const saved = slides.map((el) => ({ el, style: el.getAttribute('style'), inert: el.hasAttribute('inert'), hidden: el.getAttribute('aria-hidden'), cls: el.getAttribute('class') }));
  const hadReady = stack.hasAttribute('data-cf-ready');
  let current = Math.max(0, slides.findIndex((el) => el.hasAttribute('data-current')));
  let running = null; // 正在淡入的那一次:{ from, to, animation }
  let dead = false;

  // 改幻灯片样式的那一下先关掉它们身上的过渡:write() 里写样式,写完强制回流让它们在没有过渡的情况下先落定,再还原每张原来的行内 transition
  const quiet = (write) => {
    const held = slides.map((el) => [el.style.getPropertyValue('transition'), el.style.getPropertyPriority('transition')]);
    slides.forEach((el) => el.style.setProperty('transition', 'none', 'important'));
    write();
    if (dead) return; // write() 里的步骤可能同步触发页面的回调,里面 destroy() 了:页面已经原样还原,不再回流、不再写回过渡
    void stack.offsetHeight;
    slides.forEach((el, k) => {
      if (held[k][0]) el.style.setProperty('transition', held[k][0], held[k][1]);
      else el.style.removeProperty('transition');
    });
  };
  const conceal = (el) => {
    el.style.opacity = '0';
    el.style.visibility = 'hidden';
    el.style.zIndex = '';
    el.setAttribute('aria-hidden', 'true');
    // inert 放在最后一步:加 inert 会让里面的焦点掉出去,有的浏览器同步触发页面的 blur 回调,里面可能 destroy()——
    // 到这一步以后这个函数就不再改页面了
    el.setAttribute('inert', '');
  };
  const reveal = (el) => {
    el.style.visibility = '';
    el.removeAttribute('inert');
    el.removeAttribute('aria-hidden');
  };
  quiet(() => {
    stack.setAttribute('data-cf-ready', '');
    slides.forEach((el, i) => {
      if (i === current) { reveal(el); el.style.opacity = '1'; } else conceal(el);
    });
  });

  // 提交:旧的藏起来,新的成为当前(先写好不透明,再取消淡入动画、释放 forwards),最后发事件
  const commit = () => {
    if (!running) return;
    const { from, to, animation } = running;
    running = null;
    const entering = slides[to];
    quiet(() => {
      entering.style.opacity = '1';
      entering.style.zIndex = '';
      entering.classList.remove('is-entering');
      animation?.cancel();
      // 最后才藏旧的:加 inert 会让里面的焦点掉出去,有的浏览器同步触发页面的 blur 回调,里面可能 destroy()
      conceal(slides[from]);
    });
    if (dead) return; // 销毁了:不再发事件(destroy() 已经把页面还原成没有脚本的样子)
    current = to;
    stack.dispatchEvent(new CustomEvent('crossfade', { detail: { from, to } }));
  };
  // 先把还没走完的那一次提交;提交时的事件回调里 destroy() 了、或者又开始了新的一次,返回 false(外面这次不做了)
  const settle = () => {
    if (running) commit();
    return !dead && !running;
  };

  const start = (i) => {
    if (!Number.isInteger(i) || i < 0 || i >= slides.length || i === current) return false;
    const entering = slides[i];
    // 先建淡入动画再改页面:建动画出错时(浏览器不支持、脚本出错)页面一点没动,还停在当前那张
    const animation = reduce ? null : entering.animate([{ opacity: 0 }, { opacity: 1 }], { duration, easing, fill: 'forwards' });
    quiet(() => {
      reveal(entering);
      entering.style.opacity = '0';
      entering.style.zIndex = '1';
      entering.classList.add('is-entering');
    });
    running = { from: current, to: i, animation };
    if (!animation) {
      commit();
      // 提交是同步的,事件回调里可能已经 destroy() 了、或者又切到了别的一张:那样这一次就不算数
      return !dead && current === i;
    }
    // 走完、或者被外部取消(页面暂停时全部动画被取消):都提交(提交、destroy() 先把 running 换掉,不会提交两次)
    const done = () => { if (running && running.animation === animation) commit(); };
    animation.finished.then(done, done);
    return true;
  };

  const ctl = {
    get index() { return current; },
    show(i) { return settle() && start(i); },
    next() { return settle() && start((current + 1) % slides.length); },
    prev() { return settle() && start((current - 1 + slides.length) % slides.length); },
    destroy() {
      if (dead) return;
      dead = true;
      const animation = running?.animation;
      running = null;
      animation?.cancel();
      if (!hadReady) stack.removeAttribute('data-cf-ready');
      const put = (el, name, value) => { if (value === null) el.removeAttribute(name); else el.setAttribute(name, value); };
      // 还原也先关过渡(理由同 quiet):先换成"原来的样式 + transition: none !important",强制回流,再换回原样
      for (const { el, style, inert, hidden, cls } of saved) {
        el.setAttribute('style', `${style ?? ''};transition: none !important`);
        el.toggleAttribute('inert', inert);
        put(el, 'aria-hidden', hidden);
        put(el, 'class', cls);
      }
      void stack.offsetHeight;
      for (const { el, style } of saved) put(el, 'style', style);
      if (prevs.get(stack) === ctl) prevs.delete(stack);
    },
  };
  prevs.set(stack, ctl);
  return ctl;
}
HTML
<!-- 原地交叉淡化:容器里每个子元素是一张;两张一样大、不透明时最好看。没有脚本时几张竖着排、都看得见 -->
<div class="cf-stack" id="gallery">
  <figure><img src="sea.jpg" alt="海边"><figcaption>海边的周末</figcaption></figure>
  <figure><img src="city.jpg" alt="城市夜景"><figcaption>城市夜跑</figcaption></figure>
</div>
<button type="button" id="next-photo">下一张</button>
<script type="module">
  import { crossfade } from './crossfade.js';
  const gallery = crossfade(document.getElementById('gallery'), { duration: 500 });
  document.getElementById('next-photo').addEventListener('click', () => gallery.next());
</script>

More in Page & layout

Browse all 86 effects →

Shown once per release · Always available in changelog