中文
画廊
夜航
Scroll · Vanilla JS + CSS

Adaptive header color

顶栏取色

Adapt the sticky header background and contrasting text tone to each scrolled cover.

Also searched as: 顶栏颜色跟着封面自动变, 导航栏随封面取色并切换文字深浅, 顶部导航跟随内容区换色, 自适应深浅文字的取色顶栏

AI Markdown (.md)
Placement
Navigation, Background
Mood
Refined, Soft
Trigger
Scroll
Site types
作品集, 产品官网, 电商展示, 个人网站

How it works & accessibility

Probes which data-header-color section sits under the sticky header, updates background color transitions, and automatically selects dark or light foreground text via CSS contrast-color with a relative-luminance fallback.

Best for: Navigation, Background (Scroll).

Reduced motion: 取消颜色过渡动画,跨过封面边界时直接切换顶栏背景与对比文字颜色

Mobile & touch: 与桌面一致;各封面区块与顶栏留出足够内边距,确保标题不被重叠的顶栏遮住

Key parameters

ParameterKeyDefaultRangeNotes
变色时长duration320ms——
缓动easingcubic-bezier(0.22, 1, 0.36, 1)——

Ready-to-paste AI prompt

Add “Adaptive header color” to the navigation in my project: Probes which data-header-color section sits under the sticky header, updates background color transitions, and automatically selects dark or light foreground text via CSS contrast-color with a relative-luminance fallback.
Parameters: duration: 320ms, 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/adaptive-header-color.md (canonical specification and reference code).

Dependency-free reference code

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;
  }
}
JavaScript
// 顶栏取色(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;
    },
  };
}
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>

Shown once per release · Always available in changelog