中文
纸间把夜晚
留给阅读。
Page & layout · Vanilla JS + CSS

Circle reveal theme toggle

圆形扩散换肤

A new theme expands from its button as a circle, then shrinks back on the return trip.

Also searched as: 切换深色模式时新颜色从按钮处圆形扩散开, 暗黑模式切换时画一个圆铺满换肤区域, 主题切换的圆形扩散过渡, 点夜间模式按钮整页像水波一样换色

AI Markdown (.md)
Placement
Navigation, Button
Mood
Dramatic, Playful
Trigger
点击
Site types
个人网站, 博客, 作品集

How it works & accessibility

The reference uses native View Transitions and a circular clip from the button to the farthest viewport corner; only the selected region changes theme, unsupported browsers and reduced motion switch instantly, and the looping card uses isolated layers instead of capturing the whole page.

Best for: Navigation, Button (点击).

Reduced motion: 直接换主题,不扩散

Mobile & touch: 和桌面一样;按钮在屏幕一角时圆要长得更大,时长可以长一点

Key parameters

ParameterKeyDefaultRangeNotes
扩散的时长duration600ms——
缓动easingcubic-bezier(0.4, 0, 0.2, 1)——

Ready-to-paste AI prompt

Add “Circle reveal theme toggle” to the navigation in my project: The reference uses native View Transitions and a circular clip from the button to the farthest viewport corner; only the selected region changes theme, unsupported browsers and reduced motion switch instantly, and the looping card uses isolated layers instead of capturing the whole page.
Parameters: duration: 600ms, 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/theme-circle-reveal.md (canonical specification and reference code).

Dependency-free reference code

CSS
/* 颜色只作用于 .tcr 及其子元素,不更改站点主题。可自行覆盖四个变量。 */
.tcr { --tcr-paper: #faf9f6; --tcr-ink: #24252b; background: var(--tcr-paper); color: var(--tcr-ink); }
.tcr[data-theme="dark"] { --tcr-paper: #24252b; --tcr-ink: #faf9f6; }
/* 只在本次原生转场期间关掉默认交叉淡化,旧/新截图的堆叠方向决定扩散还是收回。 */
html[data-tcr-direction]::view-transition-old(root),
html[data-tcr-direction]::view-transition-new(root) { animation: none; mix-blend-mode: normal; }
html[data-tcr-direction="dark"]::view-transition-old(root) { z-index: 1; }
html[data-tcr-direction="dark"]::view-transition-new(root) { z-index: 2; }
html[data-tcr-direction="light"]::view-transition-old(root) { z-index: 2; }
html[data-tcr-direction="light"]::view-transition-new(root) { z-index: 1; }
JavaScript
// 圆形扩散换肤 · 原生 View Transitions,本站原创实现,没有复制第三方代码。
// root 是要换肤的区域(可传 document.documentElement),按钮必须是原生 button;只改 root 的 data-theme。
// 搭配 theme-circle-reveal.css,明/暗主题分别放在 .tcr 与 .tcr[data-theme="dark"] 的变量里。
// 点击时从按钮中心画圆,半径按视口最远角计算;换回浅色时旧的深色截图收回按钮。
// 不支持 API、减少动态:直接换色,不假装动画。一次只允许一个此类转场,忙碌时 toggle 返回 false。
// 返回 toggle(): Promise<boolean>、destroy()。销毁跳过截图动画;未执行的更新不会在销毁后晚到。
// 数据加载应在调用前完成;此函数不处理请求。View Transitions 会短暂截取页面,不用于卡片墙的自动循环。
const instances = new WeakMap();
let active = null;
export function themeCircleReveal(root, button, {
  duration = 600,
  easing = 'cubic-bezier(0.4, 0, 0.2, 1)',
} = {}) {
  instances.get(root)?.destroy();
  let dead = false, busy = false, transition = null, animation = null;
  const pressed = button.getAttribute('aria-pressed');
  button.setAttribute('aria-pressed', String(root.dataset.theme === 'dark'));
  const commit = (dark) => {
    if (dead) return false;
    root.dataset.theme = dark ? 'dark' : 'light';
    button.setAttribute('aria-pressed', String(dark));
    return true;
  };
  const toggle = async () => {
    if (dead || busy || active) return false;
    const dark = root.dataset.theme !== 'dark';
    if (!document.startViewTransition || matchMedia('(prefers-reduced-motion: reduce)').matches) return commit(dark);
    busy = true; active = ctl;
    const html = document.documentElement;
    const oldDirection = html.getAttribute('data-tcr-direction');
    html.setAttribute('data-tcr-direction', dark ? 'dark' : 'light');
    const r = button.getBoundingClientRect();
    const x = r.left + r.width / 2, y = r.top + r.height / 2;
    const radius = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y));
    let changed = false;
    try {
      transition = document.startViewTransition(() => { changed = commit(dark); });
      // skipped/销毁时 ready 会拒绝,finished 仍须接住;更新本身由浏览器执行。
      try {
        await transition.ready;
        if (!dead) {
          const small = `circle(0px at ${x}px ${y}px)`, large = `circle(${radius}px at ${x}px ${y}px)`;
          animation = html.animate({ clipPath: dark ? [small, large] : [large, small] }, {
            duration, easing, pseudoElement: dark ? '::view-transition-new(root)' : '::view-transition-old(root)',
          });
          await animation.finished.catch(() => undefined);
        }
      } catch { /* 浏览器跳过截图:更新仍会完成,不另造动画。 */ }
      await transition.finished;
      return changed;
    } finally {
      busy = false; transition = null; animation = null;
      if (active === ctl) {
        active = null;
        if (oldDirection === null) html.removeAttribute('data-tcr-direction'); else html.setAttribute('data-tcr-direction', oldDirection);
      }
    }
  };
  const click = () => { toggle().catch(() => undefined); };
  const ctl = { toggle, destroy() {
    if (dead) return; dead = true;
    button.removeEventListener('click', click); transition?.skipTransition(); animation?.cancel();
    if (pressed === null) button.removeAttribute('aria-pressed'); else button.setAttribute('aria-pressed', pressed);
    if (instances.get(root) === ctl) instances.delete(root);
  } };
  instances.set(root, ctl); button.addEventListener('click', click); return ctl;
}
HTML
<!-- root 可以是区域,也可以是整页的 html;这里只切换文章区域,不改变站点其他地方。 -->
<section class="tcr" data-theme="light">
  <button type="button" aria-label="深色模式" aria-pressed="false">◐</button>
  <h2>夜读</h2><p>留一点时间,读完今天这一页。</p>
</section>
<script type="module">
  import { themeCircleReveal } from './theme-circle-reveal.js';
  const root = document.querySelector('.tcr');
  const theme = themeCircleReveal(root, root.querySelector('button'), { duration: 600 });
  // 按钮支持鼠标、回车和空格;路由卸载时 theme.destroy()。
</script>

More in Page & layout

Browse all 86 effects →

Shown once per release · Always available in changelog