# 顶栏取色（Adaptive header color）

- 俗称：顶栏颜色跟着封面自动变；导航栏随封面取色并切换文字深浅；顶部导航跟随内容区换色；自适应深浅文字的取色顶栏
- 用在：导航、背景（作品集、产品官网、电商展示、个人网站）
- 触发：滚动
- 感觉：高级、柔和
- 版本：1，更新于 2026-12-01

## 原理

每个内容区在 data-header-color 标出主题色；脚本在滚动时定位顶栏探针点所在的区块并更新 --ahc-bg，优先使用 CSS contrast-color() 计算前景色，同时用 CIE XYZ 相对亮度公式（阈值 0.17913）算出 #000000 或 #ffffff 作为全浏览器兜底，并通过 CSS 过渡平滑换色；减少动态时直接切色。

适合：作品集长卷、展览官网、品牌主题页：每个章节有自己的主题背景色，顶栏一路平滑换色并与当前章节保持高对比度。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 变色时长 | 320ms | 120–700ms |
| `easing` | 缓动 | cubic-bezier(0.22, 1, 0.36, 1) | — |

## 质量要求

- 开启"减少动态"时：取消颜色过渡动画，跨过封面边界时直接切换顶栏背景与对比文字颜色。
- 手机上：与桌面一致；各封面区块与顶栏留出足够内边距，确保标题不被重叠的顶栏遮住。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

## 提示词（可以直接交给 AI）

```text
请在我的项目里给导航加上「顶栏取色」（Adaptive header color）效果：每个内容区在 data-header-color 标出主题色；脚本在滚动时定位顶栏探针点所在的区块并更新 --ahc-bg，优先使用 CSS contrast-color() 计算前景色，同时用 CIE XYZ 相对亮度公式（阈值 0.17913）算出 #000000 或 #ffffff 作为全浏览器兜底，并通过 CSS 过渡平滑换色；减少动态时直接切色。
参数：变色时长 320ms，缓动 cubic-bezier(0.22, 1, 0.36, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/adaptive-header-color.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 顶栏取色：每个封面区块用 data-header-color 指定颜色，顶栏自动取色并切换黑/白文字 -->
<header class="ahc-bar" style="display: flex; align-items: center; justify-content: space-between; height: 56px; padding: 0 24px;">
  <strong>动廊展厅</strong>
  <span>精选</span>
</header>
<section data-header-color="#1e2942" style="min-height: 70vh; padding: 72px 24px; background: #1e2942; color: #fff;">深蓝封面</section>
<section data-header-color="#f4e8c1" style="min-height: 70vh; padding: 72px 24px; background: #f4e8c1; color: #141519;">暖白封面</section>
<section data-header-color="#184237" style="min-height: 70vh; padding: 72px 24px; background: #184237; color: #fff;">墨绿封面</section>
<script type="module">
  import { adaptiveHeaderColor } from './adaptive-header-color.js';
  adaptiveHeaderColor(document.querySelector('.ahc-bar'), { duration: 320 });
</script>
```

CSS：

```css
/* 顶栏取色（Adaptive header color）：配合 adaptive-header-color.js。
   优先用现代 CSS contrast-color() 自动取反差文字色，同时由脚本注入高对比 --ahc-fg 作为全浏览器兜底。 */
:where(.ahc-bar) {
  --ahc-duration: 320ms;
  --ahc-easing: cubic-bezier(0.22, 1, 0.36, 1);
  --ahc-bg: #1e2942;
  --ahc-fg: #ffffff;
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: var(--ahc-bg);
  color: var(--ahc-fg);
  transition:
    background-color var(--ahc-duration) var(--ahc-easing),
    color var(--ahc-duration) var(--ahc-easing);
}

@supports (color: contrast-color(red)) {
  .ahc-bar {
    color: contrast-color(var(--ahc-bg));
  }
}

@media (prefers-reduced-motion: reduce) {
  .ahc-bar:not(.ahc-force) {
    transition: none;
  }
}
```

JS（原生，不依赖任何库）：

```js
// 顶栏取色（Adaptive header color）· 原生 JS，不依赖任何库。
// 用法：吸顶顶栏加 class="ahc-bar"，各封面区块写 data-header-color="#1e2942"，
// 调用 adaptiveHeaderColor(header, { duration: 320, easing: 'cubic-bezier(0.22, 1, 0.36, 1)', root })。
// 返回 { update(), destroy() }。

/**
 * @param {HTMLElement} header
 * @param {{ duration?: number, easing?: string, root?: Window | HTMLElement | null, ignoreReducedMotion?: boolean }} [options]
 */
export function adaptiveHeaderColor(header, {
  duration = 320,
  easing = 'cubic-bezier(0.22, 1, 0.36, 1)',
  root = null,
  ignoreReducedMotion = false,
} = {}) {
  if (!(header instanceof Element)) return null;
  let destroyed = false;
  const dur = Math.max(0, Number(duration) || 320);
  const easeStr = String(easing);
  const container = root || header.closest('.ahc-view') || document;
  const scroller = root || header.closest('.ahc-view') || window;

  header.classList.add('ahc-bar');
  if (ignoreReducedMotion) header.classList.add('ahc-force');
  header.style.setProperty('--ahc-duration', `${dur}ms`);
  header.style.setProperty('--ahc-easing', easeStr);

  const parseRgb = (color) => {
    const s = String(color || '').trim();
    const hex3 = /^#([0-9a-f]{3})$/i.exec(s);
    if (hex3) {
      const [r, g, b] = hex3[1].split('').map((c) => parseInt(c + c, 16));
      return [r, g, b];
    }
    const hex6 = /^#([0-9a-f]{6})$/i.exec(s);
    if (hex6) {
      const n = parseInt(hex6[1], 16);
      return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
    }
    const rgb = /^rgba?\(\s*(\d+)\s*[,\s]\s*(\d+)\s*[,\s]\s*(\d+)/i.exec(s);
    if (rgb) return [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])];
    return null;
  };

  const contrastFor = (color) => {
    const rgb = parseRgb(color);
    if (!rgb) return { fg: '#ffffff', tone: 'dark' };
    const lin = (c) => {
      const v = c / 255;
      return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
    };
    const lum = 0.2126 * lin(rgb[0]) + 0.7152 * lin(rgb[1]) + 0.0722 * lin(rgb[2]);
    return lum > 0.17913 ? { fg: '#000000', tone: 'light' } : { fg: '#ffffff', tone: 'dark' };
  };

  const update = () => {
    if (destroyed) return;
    const sections = [...container.querySelectorAll('[data-header-color]')];
    if (sections.length === 0) return;
    const hr = header.getBoundingClientRect();
    const probeY = hr.top + hr.height * 0.5;
    let active = sections[0];
    for (const sec of sections) {
      const sr = sec.getBoundingClientRect();
      if (sr.top <= probeY && sr.bottom > probeY) {
        active = sec;
        break;
      }
      if (sr.top <= probeY) active = sec;
    }
    const bg = active.getAttribute('data-header-color');
    if (!bg) return;
    const { fg, tone } = contrastFor(bg);
    header.style.setProperty('--ahc-bg', bg);
    header.style.setProperty('--ahc-fg', fg);
    header.dataset.tone = tone;
  };

  let ticking = false;
  const onScroll = () => {
    if (ticking || destroyed) return;
    ticking = true;
    requestAnimationFrame(() => {
      ticking = false;
      update();
    });
  };

  const ro = new ResizeObserver(update);
  ro.observe(header);
  scroller.addEventListener('scroll', onScroll, { passive: true });
  update();

  return {
    update,
    destroy() {
      if (destroyed) return;
      destroyed = true;
      scroller.removeEventListener('scroll', onScroll);
      ro.disconnect();
      header.classList.remove('ahc-force');
      header.style.removeProperty('--ahc-duration');
      header.style.removeProperty('--ahc-easing');
      header.style.removeProperty('--ahc-bg');
      header.style.removeProperty('--ahc-fg');
      delete header.dataset.tone;
    },
  };
}
```

## 出处

- 本站原创实现：结合 contrast-color() 渐进增强与 WCAG 相对亮度阈值计算自动对比色，未使用第三方代码
