# 下滑隐藏顶栏（Hide-on-scroll header）

- 俗称：往下滑导航栏藏起来，往上滑又出来；滚动时顶部导航自动隐藏；看文章时顶栏收起来让出地方；智能隐藏的顶栏
- 用在：导航（个人网站、博客、作品集）
- 触发：滚动
- 感觉：利落
- 版本：2，更新于 2026-10-23

## 原理

每次滚动都和上一次算数的位置比：往下滑（超过几像素）就把顶栏往上推出屏幕，往上滑就拉回来；离页面顶上很近时一直显示。滑动用 CSS 过渡，只动位移。

适合：个人网站、博客的顶栏；长文章页和手机上最有用：读的时候让出地方，想去别的页面时往上一滑就在。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 时长 | 300ms | 150–700ms |
| `easing` | 缓动 | cubic-bezier(0.2, 0.7, 0.3, 1) | — |

## 质量要求

- 开启"减少动态"时：不滑动，改成淡出淡入；藏着时鼠标点不到，键盘选中顶栏里的链接时马上出现。
- 手机上：手机上最有用（屏幕小，让出地方给内容）；位置限制在能滚的范围里，iOS 滚过头回弹不会让它冒出来。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给导航加上「下滑隐藏顶栏」（Hide-on-scroll header）效果：每次滚动都和上一次算数的位置比：往下滑（超过几像素）就把顶栏往上推出屏幕，往上滑就拉回来；离页面顶上很近时一直显示。滑动用 CSS 过渡，只动位移。
参数：时长 300ms，缓动 cubic-bezier(0.2, 0.7, 0.3, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/hide-on-scroll-header.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 下滑隐藏顶栏：顶栏加 class="autohide"（放在 body 的最前面，sticky 才贴得住顶上）；往下滑藏起来，往上滑出现 -->
<header class="autohide" style="display: flex; align-items: center; gap: 24px; height: 56px; padding: 0 24px; background: #fff; border-bottom: 1px solid #eee">
  <a href="/">北煜ii</a>
  <nav style="display: flex; gap: 16px; margin-left: auto">
    <a href="/posts/">文章</a>
    <a href="/works/">作品</a>
    <a href="/about/">关于</a>
  </nav>
</header>
<main>……</main>
<style>
  /* 页内链接跳到标题时不被顶栏挡住 */
  html { scroll-padding-top: 56px; }
</style>
<script type="module">
  import { hideOnScroll } from './hide-on-scroll-header.js';
  hideOnScroll(document.querySelector('.autohide'));
</script>
```

CSS：

```css
/* 下滑隐藏顶栏（Hide-on-scroll header）的样式，配合 hide-on-scroll-header.js。
   改写自 Animation Handbook 的 Hide-on-Scroll Header（MIT License，Copyright (c) 2026 Matin Monshizadeh）。
   顶栏加 class="autohide"，默认用 position: sticky 放在顶上；顶栏自己写了 position（比如 fixed）就用它自己的（这几样默认值写在 :where() 里，
   什么选择器都盖得过它；用 fixed 的话页面上面要留出顶栏的高度）。
   藏起来是往上推出它自己的高度再多 2px（下边框一起出去；顶栏有往下的影子时，把 2px 改成影子伸出来的距离，不然藏起来时屏幕顶上会留一道影子），
   只动 translate，不盖掉顶栏原来的 transform。
   - 键盘选中顶栏里的链接时一直在（:focus-within）。顶栏里有悬停展开的菜单时，菜单开着别藏：把 :hover（或者菜单打开时加的 class）
     并进下面的 :not()，比如 .autohide.is-away:not(:focus-within, :hover)。
   - 点页内链接跳到某个标题时别被顶栏挡住：给 html 加 scroll-padding-top，值是顶栏的高度。
   - 顶栏里有这一页最要紧的按钮（结账、保存）时，别用这个效果。
   - 这个 class 会重写顶栏的 transition（transition 只能写一行，后写的盖掉先写的）：顶栏原来就有过渡的，把原来的几项并进这一行。
   - 开启"减少动态"时：不滑动，淡出淡入；藏着时鼠标点不到（pointer-events: none），键盘照样能选中、选中就出现。 */
:where(.autohide) {
  position: sticky;
  top: 0;
  z-index: 10;
}
.autohide {
  --autohide-duration: 300ms;
  --autohide-easing: cubic-bezier(0.2, 0.7, 0.3, 1);
  transition: translate var(--autohide-duration) var(--autohide-easing);
}
.autohide.is-away:not(:focus-within) {
  translate: 0 calc(-100% - 2px);
}
@media (prefers-reduced-motion: reduce) {
  .autohide { transition: opacity var(--autohide-duration) linear; }
  .autohide.is-away:not(:focus-within) { translate: none; opacity: 0; pointer-events: none; }
}
```

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

```js
// 下滑隐藏顶栏（Hide-on-scroll header）· 原生 JS，不依赖任何库。
// 改写自 Animation Handbook 的 Hide-on-Scroll Header（MIT License，Copyright (c) 2026 Matin Monshizadeh）：
// 往下滑把顶栏整条推出屏幕，往上滑拉回来；离页面顶上不到两条顶栏高时一直在。滑动不到 threshold 像素的抖动（触控板、手指常有）不算，
// 只有算数的那一次才记下位置，所以慢慢滑也会累积起来；位置先限制在 0 到能滚的最大值之间（iOS 滚过头回弹的那一下不算往上滑）。
// 默认的时长和缓动来自它。
// bar 是顶栏（配合 hide-on-scroll-header.css）：顶栏加 class="autohide"，用 position: sticky（或 fixed）放在顶上。
// 脚本只切换 class="is-away"、把时长和缓动写到顶栏的 CSS 变量上；滑动本身是 CSS 过渡，只动 translate，不引起重新排版。
// 键盘选中顶栏里的链接时顶栏一直在（CSS 的 :focus-within）。root 是滚动的容器，默认整个页面（window）。
// 返回 { update(), destroy() }。
// 开启"减少动态"时：脚本照常判断往哪边滑，CSS 让顶栏淡出淡入、不滑动。
/**
 * @param {HTMLElement} bar
 * @param {{ duration?: number, easing?: string, threshold?: number, root?: Window | HTMLElement }} [options]
 */
export function hideOnScroll(bar, {
  duration = 300,
  easing = 'cubic-bezier(0.2, 0.7, 0.3, 1)',
  threshold = 6,
  root = window,
} = {}) {
  bar.style.setProperty('--autohide-duration', `${duration}ms`);
  bar.style.setProperty('--autohide-easing', easing);
  // 现在滚到哪里：限制在 0 到能滚的最大值之间
  const position = () => {
    const y = root === window ? scrollY : root.scrollTop;
    const max = root === window ? document.documentElement.scrollHeight - innerHeight : root.scrollHeight - root.clientHeight;
    return Math.min(Math.max(y, 0), Math.max(max, 0));
  };
  let near = bar.offsetHeight * 2; // 离顶上多近时一直显示：两条顶栏高
  let away = false;
  let last = position();
  const set = (on) => {
    if (on === away) return;
    away = on;
    bar.classList.toggle('is-away', on);
  };
  const update = () => {
    const y = position();
    if (y <= near) { set(false); last = y; return; }
    const dy = y - last;
    if (Math.abs(dy) < threshold) return; // 抖动不算；last 不变，慢慢滑会累积起来
    set(dy > 0);
    last = y;
  };
  let ticking = false;
  const schedule = () => {
    if (ticking) return;
    ticking = true;
    requestAnimationFrame(() => {
      ticking = false;
      update();
    });
  };
  root.addEventListener('scroll', schedule, { passive: true });
  // 顶栏变高（换行、字体换了）时，"离顶上多近"跟着变
  const resized = new ResizeObserver(() => { near = bar.offsetHeight * 2; });
  resized.observe(bar);
  update();

  return {
    update,
    destroy() {
      root.removeEventListener('scroll', schedule);
      resized.disconnect();
      bar.classList.remove('is-away');
      bar.style.removeProperty('--autohide-duration');
      bar.style.removeProperty('--autohide-easing');
    },
  };
}
```

## 出处

- Animation Handbook · Hide-on-Scroll Header（https://github.com/matinmonshizadeh/animation-handbook/tree/main/animations/01-scroll-based/hide-on-scroll-header，MIT）：改写自它的做法和默认值（往下滑藏起来、往上滑出现、离顶上两条顶栏高以内一直在；6px 以内的抖动不算、只有算数的一次才记下位置；位置限制在能滚的范围里；藏起来推出自身高度再多 2px；键盘选中时出现；减少动态时淡出淡入；300ms、cubic-bezier(0.2, 0.7, 0.3, 1)）；改用 translate 属性，不盖掉顶栏原来的 transform，减少动态时藏着的顶栏点不到
