中文

作品按分类看

Click & feedback · Vanilla JS + CSS

Sliding tab indicator

标签下划线滑动

Click a tab and the underline slides over to it, taking that tab's width.

Also searched as: 点标签时下面的线滑过去, 选中项的下划线跟着移动, 标签页切换时下划线跟着走, 分段切换的滑块指示条

AI Markdown (.md)
Placement
Navigation
Mood
Crisp
Trigger
点击
Site types
个人网站, 作品集, 工具站

How it works & accessibility

A bar inside the role=tablist is positioned by script from the selected tab's offsetLeft and offsetWidth and moved with translate and width transitions; arrow keys, Home and End switch tabs with a roving tabindex and focus follows, panels toggle hidden, a ResizeObserver re-measures without animating, without JS the selected tab draws its own underline, and with reduced motion the bar jumps instead of sliding.

Best for: Navigation (点击).

Reduced motion: 线直接换到选中的标签下面,不滑

Mobile & touch: 和桌面一样;标签多到要横着滑时,线跟着标签一起滑

Key parameters

ParameterKeyDefaultRangeNotes
滑过去的时长duration300ms——
缓动easingcubic-bezier(0.4, 0, 0.2, 1)——

Ready-to-paste AI prompt

Add “Sliding tab indicator” to the navigation in my project: A bar inside the role=tablist is positioned by script from the selected tab's offsetLeft and offsetWidth and moved with translate and width transitions; arrow keys, Home and End switch tabs with a roving tabindex and focus follows, panels toggle hidden, a ResizeObserver re-measures without animating, without JS the selected tab draws its own underline, and with reduced motion the bar jumps instead of sliding.
Parameters: duration: 300ms, 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/tab-indicator.md (canonical specification and reference code).

Dependency-free reference code

CSS
/* 标签下划线滑动(Sliding tab indicator):配合 tab-indicator.js。
   没有脚本时:选中的标签自己画一条下划线(::after);脚本接手后标签栏有 ti-js,改用那条会滑的线(.ti-bar)。
   --ti-height:线的粗细;--ti-color:线的颜色(默认跟着文字颜色)。时长、缓动由脚本的选项写到标签栏上(--ti-duration、--ti-easing)。
   开启"减少动态"时:线直接到位、不滑。 */
:where(.ti) {
  --ti-duration: 300ms;
  --ti-easing: cubic-bezier(0.4, 0, 0.2, 1);
  --ti-height: 2px;
  --ti-color: currentColor;
  position: relative;
}
.ti > [role="tab"] {
  position: relative;
}
.ti:not(.ti-js) > [role="tab"][aria-selected="true"]::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: var(--ti-height);
  border-radius: var(--ti-height);
  background: var(--ti-color);
}
.ti-bar {
  display: none;
  position: absolute;
  left: 0;
  bottom: 0;
  height: var(--ti-height);
  border-radius: var(--ti-height);
  background: var(--ti-color);
  pointer-events: none;
}
.ti.ti-js > .ti-bar {
  display: block;
  transition: translate var(--ti-duration) var(--ti-easing), width var(--ti-duration) var(--ti-easing);
}
.ti.ti-instant > .ti-bar {
  transition: none;
}
@media (prefers-reduced-motion: reduce) {
  .ti.ti-js:not(.ti-force) > .ti-bar { transition: none; }
}
JavaScript
// 标签下划线滑动(Sliding tab indicator)· 原生 JS,不依赖任何库。
// 同类效果见 Animation Handbook 的 segmented-control(MIT);本站按通用做法自己实现,没有复制代码。
// 用法:标签栏写成 role="tablist",标签是里面直接的 <button role="tab">(aria-selected 标出选中的那个,aria-controls 指向各自的面板),
// 最后放 <span class="ti-bar" aria-hidden="true"></span>,再调 tabIndicator(标签栏)。配合 tab-indicator.css。
// - 点哪个标签,线就滑到它下面、变成它的宽度(translate 和 width 的 CSS 过渡);选中的标签 aria-selected="true",
//   别的标签 tabindex="-1"(标签页的写法:Tab 只停在选中的那个上),面板(aria-controls 指向的元素)跟着显示、隐藏(hidden)。
// - 键盘:标签上按左右方向键换到上一个、下一个(到头了绕回来),Home、End 到第一个、最后一个;换完焦点跟过去。
// - 标签栏或标签变宽变窄(窗口变了、字体加载完)时重新量,线直接到位、不播过渡。
// - 没有脚本时(tab-indicator.css):选中的标签自己画一条下划线;脚本接手后给标签栏加 ti-js,改用这条会滑的线。
// - 选项:duration(滑过去的时长,ms)、easing(缓动);开启"减少动态"时线直接到位、不滑。ignoreReducedMotion 只给演示用。
// - 支持的布局:标签栏有定位(tab-indicator.css 里默认 position: relative),标签是它直接的子元素、横着排;标签少于 2 个或没有 .ti-bar 时什么都不改,返回 null。
// - 选中的标签换了以后,在标签栏上发 tabchange 事件(detail.index、detail.tab),发的时候属性、面板、线都已经是新的样子。
// 返回 { select(第几个), destroy() }:select 用代码切换(和点一下一样);destroy 摘掉监听和观察,拿掉 ti-js 和写上去的样式,之后不再改页面。
export function tabIndicator(tablist, {
  duration = 300,
  easing = 'cubic-bezier(0.4, 0, 0.2, 1)',
  ignoreReducedMotion = false,
} = {}) {
  const tabs = [...tablist.querySelectorAll(':scope > [role="tab"]')];
  const bar = tablist.querySelector(':scope > .ti-bar');
  if (!bar || tabs.length < 2) return null;
  let destroyed = false;
  let current = Math.max(0, tabs.findIndex((t) => t.getAttribute('aria-selected') === 'true'));

  const panelOf = (t) => {
    const id = t.getAttribute('aria-controls');
    return id ? document.getElementById(id) : null;
  };
  const mark = () => tabs.forEach((t, k) => {
    const on = k === current;
    t.setAttribute('aria-selected', String(on));
    t.tabIndex = on ? 0 : -1;
    const panel = panelOf(t);
    if (panel) panel.hidden = !on;
  });
  // 把线放到选中的标签下面。instant:先关掉过渡、放好、强制回流、再恢复过渡("放好"本身不会触发一次过渡)
  const place = (instant) => {
    const t = tabs[current];
    if (instant) tablist.classList.add('ti-instant');
    bar.style.width = `${t.offsetWidth}px`;
    bar.style.translate = `${t.offsetLeft}px 0`;
    if (instant) {
      void bar.offsetWidth;
      tablist.classList.remove('ti-instant');
    }
  };
  // 换到第 i 个:属性、面板、线先换好,焦点跟过去,最后才发事件(页面收到事件时看到的已经是新的样子)
  const select = (i, focus = false) => {
    if (destroyed || !Number.isInteger(i) || i < 0 || i >= tabs.length) return;
    const changed = i !== current;
    if (changed) {
      current = i;
      mark();
      place(false);
    }
    if (focus) tabs[i].focus();
    if (changed) tablist.dispatchEvent(new CustomEvent('tabchange', { detail: { index: i, tab: tabs[i] } }));
  };
  const onClick = (event) => {
    const i = tabs.indexOf(event.target.closest?.('[role="tab"]'));
    if (i >= 0 && i !== current) select(i);
  };
  const onKey = (event) => {
    const i = tabs.indexOf(event.target.closest?.('[role="tab"]'));
    if (i < 0) return;
    const n = { ArrowRight: (i + 1) % tabs.length, ArrowLeft: (i - 1 + tabs.length) % tabs.length, Home: 0, End: tabs.length - 1 }[event.key];
    if (n === undefined) return;
    event.preventDefault();
    if (n === current) tabs[n].focus();
    else select(n, true);
  };
  // 尺寸真的变了才重新量:刚开始观察时浏览器也会回调一次,那一次不能动线(正在滑的过渡会被直接跳到终点)
  const measure = () => [tablist.clientWidth, ...tabs.map((t) => `${t.offsetLeft},${t.offsetWidth}`)].join(' ');
  let sizes = '';
  const resize = new ResizeObserver(() => {
    if (destroyed) return;
    const now = measure();
    if (now === sizes) return;
    sizes = now;
    place(true);
  });

  tablist.style.setProperty('--ti-duration', `${duration}ms`);
  tablist.style.setProperty('--ti-easing', easing);
  if (ignoreReducedMotion) tablist.classList.add('ti-force');
  mark();
  tablist.classList.add('ti-js');
  place(true);
  sizes = measure();
  tablist.addEventListener('click', onClick);
  tablist.addEventListener('keydown', onKey);
  resize.observe(tablist);
  tabs.forEach((t) => resize.observe(t));

  return {
    select: (i) => select(i),
    destroy() {
      if (destroyed) return;
      destroyed = true;
      resize.disconnect();
      tablist.removeEventListener('click', onClick);
      tablist.removeEventListener('keydown', onKey);
      tablist.classList.remove('ti-js', 'ti-force', 'ti-instant');
      tablist.style.removeProperty('--ti-duration');
      tablist.style.removeProperty('--ti-easing');
      bar.style.removeProperty('width');
      bar.style.removeProperty('translate');
    },
  };
}
HTML
<!-- 标签下划线滑动:标签栏 role="tablist",标签是里面直接的 <button role="tab">,最后放一条线;面板用 aria-controls 对上 -->
<div class="ti" role="tablist" aria-label="作品分类">
  <button role="tab" id="tab-all" aria-selected="true" aria-controls="panel-all">全部</button>
  <button role="tab" id="tab-design" aria-selected="false" aria-controls="panel-design">设计</button>
  <button role="tab" id="tab-code" aria-selected="false" aria-controls="panel-code">开发</button>
  <span class="ti-bar" aria-hidden="true"></span>
</div>
<div role="tabpanel" id="panel-all" aria-labelledby="tab-all">全部作品……</div>
<div role="tabpanel" id="panel-design" aria-labelledby="tab-design" hidden>设计作品……</div>
<div role="tabpanel" id="panel-code" aria-labelledby="tab-code" hidden>开发作品……</div>
<script type="module">
  import { tabIndicator } from './tab-indicator.js';
  tabIndicator(document.querySelector('.ti'), { duration: 300 });
</script>

More in Click & feedback

Browse all 86 effects →

Shown once per release · Always available in changelog