EN
双弹簧物理下划线
点击与反馈 · 原生 JS + CSS

弹性下划线

Elastic tab underline

切换标签时,下划线前沿先冲过头、后沿慢半拍跟上,先拉长再收拢,并带动文字和内容页联动回弹

常见大白话搜法:标签弹性下划线、带回弹的标签下划线、前沿后沿双弹簧下划线、先拉长再收拢下划线、粘滞拖拽感标签指示线

AI 专用 Markdown (.md)
适用位置
导航
气质感觉
俏皮、利落
触发方式
点击
适合网站
个人网站、作品集、产品官网、移动端网页

实现原理与无障碍底线

在 role="tablist" 中放置绝对定位的指示条 .eti-bar,左右两边各自运行一条质量为 1 的阻尼弹簧:移动方向的前沿用硬弹簧(stiffness 300、damping 20,约 0.58 阻尼比)先冲过头再回弹,后沿用软弹簧(stiffness 90、damping 17,约 0.90 阻尼比)慢半拍收拢,连点时继承实时位置与速度而不重置;将采样轨迹通过 WAAPI 作用在 .eti-bar 上,同时在 rAF 中根据下划线中心点插值出小数标签索引,驱动标签色值、1.08 倍字号缩放、过半加粗及下方内容页带过冲平移淡入淡出。

适用场景:音乐频道、信息流顶栏、内容分类导航切换:用物理弹簧把切换方向和惯性直接画在下划线上,交互手感活泼有韧性

减少动态(prefers-reduced-motion):跳过双弹簧拉长与过冲动画,切换标签后下划线、文字样式与内容页直接到位

移动端与触屏:与桌面一致;触屏点按或尺寸变化时自动重算各标签几何位置,快速连点保留当前速度平滑接管

关键可调参数

参数键名默认值建议范围说明
前沿刚度leadStiffness300——
前沿阻尼leadDamping20——
后沿刚度trailStiffness90——
后沿阻尼trailDamping17——

可直接复制给 AI(Cursor / Claude / v0)的提示词

请在我的项目里给导航加上「弹性下划线」(Elastic tab underline)效果:在 role="tablist" 中放置绝对定位的指示条 .eti-bar,左右两边各自运行一条质量为 1 的阻尼弹簧:移动方向的前沿用硬弹簧(stiffness 300、damping 20,约 0.58 阻尼比)先冲过头再回弹,后沿用软弹簧(stiffness 90、damping 17,约 0.90 阻尼比)慢半拍收拢,连点时继承实时位置与速度而不重置;将采样轨迹通过 WAAPI 作用在 .eti-bar 上,同时在 rAF 中根据下划线中心点插值出小数标签索引,驱动标签色值、1.08 倍字号缩放、过半加粗及下方内容页带过冲平移淡入淡出。
参数:前沿刚度 300,前沿阻尼 20,后沿刚度 90,后沿阻尼 17。
要求:保留原有的内容和布局;系统开启"减少动态"时直接显示最终状态;脚本出错或没有执行时内容仍然可见。
参考:https://donglang.linter.top/effects/elastic-tab-indicator.md(原理、参数和参考代码)

原生无依赖参考代码

CSS
/* 弹性下划线(双弹簧前沿过冲 + 后沿跟上 + 标签/内容页联动)参考样式
   色板与尺寸按要求定义:背景 #F6F5F2、分隔线 2px rgba(21,23,28,0.07)、
   标签 38px / padding-inline 24px、文字色 #7B808C -> #15171C、下划线 7px 圆角 4px #E2603A */
.eti-shell {
  background: #F6F5F2;
  color: #15171C;
  padding: 20px 24px 28px;
}

.eti-toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.eti-slow-toggle {
  appearance: none;
  border: 1px solid rgba(21, 23, 28, 0.14);
  background: transparent;
  color: #7B808C;
  font: 500 13px/1.2 system-ui, -apple-system, sans-serif;
  padding: 6px 12px;
  border-radius: 999px;
  cursor: pointer;
}

.eti-slow-toggle[aria-pressed='true'] {
  background: #E2603A;
  border-color: #E2603A;
  color: #FFFFFF;
}

.eti-tabs {
  position: relative;
  display: inline-flex;
  align-items: center;
  border-bottom: 2px solid rgba(21, 23, 28, 0.07);
}

.eti-tab {
  position: relative;
  appearance: none;
  background: none;
  border: 0;
  padding: 12px 24px 16px;
  font-size: 38px;
  line-height: 1.25;
  color: #7B808C;
  cursor: pointer;
  white-space: nowrap;
}

.eti-label {
  position: relative;
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  color: inherit;
  transform-origin: center center;
  will-change: transform;
}

/* 预留 700 字重宽度,避免缩放和加粗时相邻标签发生横向挤压抖动 */
.eti-label::after {
  content: attr(data-text);
  font-weight: 700;
  height: 0;
  overflow: hidden;
  visibility: hidden;
  pointer-events: none;
  user-select: none;
}

.eti-tab[aria-selected='true'] {
  color: #15171C;
}

.eti-tab[aria-selected='true'] .eti-label {
  font-weight: 700;
  scale: 1.08;
}

.eti-tab:focus-visible {
  outline: 2px solid #E2603A;
  outline-offset: 2px;
  border-radius: 4px;
}

/* 无脚本时的静态高亮下划线,宽度同样只贴合文字本身 */
.eti-tabs:not([data-eti-ready]) .eti-tab[aria-selected='true'] .eti-label::before {
  content: '';
  position: absolute;
  left: 0;
  bottom: -18px;
  width: 100%;
  height: 7px;
  border-radius: 4px;
  background: #E2603A;
}

.eti-bar {
  position: absolute;
  left: 0;
  bottom: -2px;
  height: 7px;
  width: 0;
  border-radius: 4px;
  background: #E2603A;
  pointer-events: none;
  will-change: translate, width;
}

.eti-tabs:not([data-eti-ready]) .eti-bar {
  display: none;
}

.eti-pages {
  overflow: hidden;
  margin-top: 20px;
}

.eti-track {
  display: flex;
  width: 100%;
  will-change: translate;
}

.eti-page {
  flex: 0 0 100%;
  width: 100%;
  box-sizing: border-box;
  padding: 16px 0;
  will-change: opacity;
}
JavaScript
// 弹性下划线:原生实现(约 190 行,无依赖)
// 左右两条边各自运行一条 mass=1 的阻尼弹簧:前沿硬弹簧过冲,后沿软弹簧慢半拍跟上;
// 快速连点保留实时位置与速度;下划线中心点插值联动标签色彩/缩放/粗细与下方内容页平移淡入淡出。
const SETTLE_MS = 850;
const SUBSTEP_SEC = 1 / 240;
const KEYFRAME_COUNT = 102;
const MUTED_RGB = [123, 128, 140]; // #7B808C
const ACTIVE_RGB = [21, 23, 28]; // #15171C

export function elasticTabIndicator(
  tablist,
  {
    leadStiffness = 300,
    leadDamping = 20,
    trailStiffness = 90,
    trailDamping = 17,
    pages = null,
    timeScale = 1,
    ignoreReducedMotion = false,
  } = {},
) {
  const tabs = Array.from(tablist.querySelectorAll('[role="tab"]'));
  const bar = tablist.querySelector('.eti-bar');
  if (!tabs.length || !bar) return { select() {}, setTimeScale() {}, destroy() {} };

  const track = pages?.querySelector('.eti-track') ?? null;
  const pageNodes = pages ? Array.from(pages.querySelectorAll('.eti-page')) : [];
  const reducedQuery = typeof window !== 'undefined' ? window.matchMedia?.('(prefers-reduced-motion: reduce)') : null;
  const isReduced = () => !ignoreReducedMotion && Boolean(reducedQuery?.matches);

  let activeIndex = Math.max(
    0,
    tabs.findIndex((t) => t.getAttribute('aria-selected') === 'true'),
  );
  let curL = 0;
  let curR = 0;
  let velL = 0;
  let velR = 0;
  let currentScale = Number.isFinite(timeScale) && timeScale > 0 ? timeScale : 1;
  let activeAnim = null;
  let activeSamples = null;
  let rafId = 0;
  let destroyed = false;

  tablist.setAttribute('data-eti-ready', '');

  function measureMetrics() {
    const rects = tabs.map((tab) => {
      const label = tab.querySelector('.eti-label') ?? tab;
      const w = label.offsetWidth;
      const l = tab.offsetLeft + (tab.offsetWidth - w) / 2;
      return { left: l, width: w, right: l + w, center: l + w / 2 };
    });
    return { rects, centers: rects.map((r) => r.center) };
  }

  function interpolateIndex(center, centers) {
    if (centers.length <= 1) return 0;
    if (center <= centers[0]) {
      const span = centers[1] - centers[0] || 1;
      return (center - centers[0]) / span;
    }
    const last = centers.length - 1;
    if (center >= centers[last]) {
      const span = centers[last] - centers[last - 1] || 1;
      return last + (center - centers[last]) / span;
    }
    for (let i = 0; i < last; i++) {
      if (center >= centers[i] && center <= centers[i + 1]) {
        const span = centers[i + 1] - centers[i] || 1;
        return i + (center - centers[i]) / span;
      }
    }
    return activeIndex;
  }

  function applyLinkage(p) {
    tabs.forEach((tab, k) => {
      const w = Math.max(0, 1 - Math.abs(k - p));
      const r = Math.round(MUTED_RGB[0] + (ACTIVE_RGB[0] - MUTED_RGB[0]) * w);
      const g = Math.round(MUTED_RGB[1] + (ACTIVE_RGB[1] - MUTED_RGB[1]) * w);
      const b = Math.round(MUTED_RGB[2] + (ACTIVE_RGB[2] - MUTED_RGB[2]) * w);
      const label = tab.querySelector('.eti-label') ?? tab;
      label.style.color = `rgb(${r} ${g} ${b})`;
      label.style.scale = (1 + 0.08 * w).toFixed(4);
      label.style.fontWeight = w > 0.5 ? '700' : '400';
    });
    if (track) track.style.translate = `${(-p * 100).toFixed(4)}% 0px`;
    pageNodes.forEach((node, k) => {
      const op = Math.max(0, 1 - Math.abs(k - p));
      node.style.opacity = op.toFixed(4);
      node.inert = op <= 0.01;
    });
  }

  function readLiveEdgeState() {
    if (!activeAnim || !activeSamples || activeAnim.playState === 'idle') return [curL, velL, curR, velR];
    const tSec = Math.max(0, Math.min(SETTLE_MS / 1000, (Number(activeAnim.currentTime) || 0) / 1000));
    const idxFloat = (tSec / (SETTLE_MS / 1000)) * (activeSamples.length - 1);
    const i0 = Math.min(activeSamples.length - 1, Math.floor(idxFloat));
    const i1 = Math.min(activeSamples.length - 1, i0 + 1);
    const frac = idxFloat - i0;
    const a = activeSamples[i0];
    const b = activeSamples[i1];
    return [
      a.xL + (b.xL - a.xL) * frac,
      a.vL + (b.vL - a.vL) * frac,
      a.xR + (b.xR - a.xR) * frac,
      a.vR + (b.vR - a.vR) * frac,
    ];
  }

  function stopAnim(commit = false) {
    if (rafId) {
      cancelAnimationFrame(rafId);
      rafId = 0;
    }
    if (activeAnim) {
      const anim = activeAnim;
      activeAnim = null;
      activeSamples = null;
      if (commit) {
        const [xL, vL, xR, vR] = [curL, velL, curR, velR];
        void [xL, vL, xR, vR];
      }
      anim.cancel();
    }
  }

  function buildDualSpringSamples(fromL, fromVL, fromR, fromVR, targetL, targetR) {
    const movingRight = (targetL + targetR) / 2 >= (fromL + fromR) / 2;
    const [kL, dL] = movingRight ? [trailStiffness, trailDamping] : [leadStiffness, leadDamping];
    const [kR, dR] = movingRight ? [leadStiffness, leadDamping] : [trailStiffness, trailDamping];
    const totalSubsteps = Math.round((SETTLE_MS / 1000) / SUBSTEP_SEC);
    const samples = [{ xL: fromL, vL: fromVL, xR: fromR, vR: fromVR }];
    let xL = fromL;
    let vL = fromVL;
    let xR = fromR;
    let vR = fromVR;
    for (let s = 1; s <= totalSubsteps; s++) {
      [xL, vL] = stepSpring(xL, vL, targetL, kL, dL, SUBSTEP_SEC);
      [xR, vR] = stepSpring(xR, vR, targetR, kR, dR, SUBSTEP_SEC);
      samples.push({ xL, vL, xR, vR });
    }
    return samples;
  }

  function syncAttributes(index) {
    tabs.forEach((tab, i) => {
      const selected = i === index;
      tab.setAttribute('aria-selected', selected ? 'true' : 'false');
      if (!tab.hasAttribute('data-eti-managed-tabindex')) {
        tab.tabIndex = selected ? 0 : -1;
      }
    });
  }

  function select(index, { animate = true } = {}) {
    if (destroyed) return;
    const clamped = Math.max(0, Math.min(tabs.length - 1, index));
    const { rects, centers } = measureMetrics();
    const target = rects[clamped];
    const [liveL, liveVL, liveR, liveVR] = readLiveEdgeState();

    activeIndex = clamped;
    syncAttributes(clamped);
    stopAnim(false);

    if (!animate || isReduced()) {
      curL = target.left;
      curR = target.right;
      velL = 0;
      velR = 0;
      bar.style.translate = `${curL}px 0px`;
      bar.style.width = `${target.width}px`;
      applyLinkage(clamped);
      return;
    }

    const samples = buildDualSpringSamples(liveL, liveVL, liveR, liveVR, target.left, target.right);
    const keyframes = [];
    for (let i = 0; i <= KEYFRAME_COUNT; i++) {
      const p = i / KEYFRAME_COUNT;
      const sample = samples[Math.round(p * (samples.length - 1))];
      const left = i === KEYFRAME_COUNT ? target.left : sample.xL;
      const width = Math.max(4, i === KEYFRAME_COUNT ? target.width : sample.xR - sample.xL);
      keyframes.push({
        offset: p,
        translate: `${left}px 0px`,
        width: `${width}px`,
      });
    }

    curL = target.left;
    curR = target.right;
    velL = 0;
    velR = 0;
    bar.style.translate = `${target.left}px 0px`;
    bar.style.width = `${target.width}px`;

    activeSamples = samples;
    activeAnim = bar.animate(keyframes, {
      duration: SETTLE_MS,
      easing: 'linear',
      fill: 'none',
    });
    activeAnim.playbackRate = currentScale;

    const myAnim = activeAnim;
    const tick = () => {
      if (destroyed || activeAnim !== myAnim || myAnim.playState === 'idle') {
        rafId = 0;
        return;
      }
      if (myAnim.playState === 'finished') {
        rafId = 0;
        activeAnim = null;
        activeSamples = null;
        applyLinkage(activeIndex);
        return;
      }
      const [xL, , xR] = readLiveEdgeState();
      applyLinkage(interpolateIndex((xL + xR) / 2, centers));
      rafId = requestAnimationFrame(tick);
    };
    applyLinkage(interpolateIndex((liveL + liveR) / 2, centers));
    rafId = requestAnimationFrame(tick);
  }

  function setTimeScale(rate) {
    currentScale = Number.isFinite(rate) && rate > 0 ? rate : 1;
    if (activeAnim) activeAnim.playbackRate = currentScale;
  }

  function onClick(event) {
    const tab = event.target instanceof Element ? event.target.closest('[role="tab"]') : null;
    const idx = tab ? tabs.indexOf(tab) : -1;
    if (idx !== -1) select(idx, { animate: true });
  }

  function onKeydown(event) {
    const idx = tabs.indexOf(document.activeElement);
    if (idx === -1) return;
    let next = -1;
    if (event.key === 'ArrowRight') next = (idx + 1) % tabs.length;
    else if (event.key === 'ArrowLeft') next = (idx - 1 + tabs.length) % tabs.length;
    else if (event.key === 'Home') next = 0;
    else if (event.key === 'End') next = tabs.length - 1;
    if (next === -1) return;
    event.preventDefault();
    tabs[next].focus();
    select(next, { animate: true });
  }

  let lastWidth = tablist.clientWidth;
  const ro = new ResizeObserver(() => {
    if (destroyed) return;
    const nextWidth = tablist.clientWidth;
    if (Math.abs(nextWidth - lastWidth) < 0.5) return;
    lastWidth = nextWidth;
    select(activeIndex, { animate: false });
  });
  ro.observe(tablist);
  tablist.addEventListener('click', onClick);
  tablist.addEventListener('keydown', onKeydown);

  const initial = measureMetrics().rects[activeIndex];
  curL = initial.left;
  curR = initial.right;
  bar.style.translate = `${initial.left}px 0px`;
  bar.style.width = `${initial.width}px`;
  syncAttributes(activeIndex);
  applyLinkage(activeIndex);

  return {
    select,
    setTimeScale,
    destroy() {
      destroyed = true;
      stopAnim(false);
      ro.disconnect();
      tablist.removeEventListener('click', onClick);
      tablist.removeEventListener('keydown', onKeydown);
      tablist.removeAttribute('data-eti-ready');
      bar.style.translate = '';
      bar.style.width = '';
      if (track) track.style.translate = '';
      tabs.forEach((tab) => {
        const label = tab.querySelector('.eti-label') ?? tab;
        label.style.color = '';
        label.style.scale = '';
        label.style.fontWeight = '';
      });
      pageNodes.forEach((node) => {
        node.style.opacity = '';
        node.inert = false;
      });
    },
  };
}

export function stepSpring(x, v, target, stiffness, damping, dt) {
  const a = -stiffness * (x - target) - damping * v;
  const nextV = v + a * dt;
  const nextX = x + nextV * dt;
  return [nextX, nextV];
}
HTML
<div class="eti-shell">
  <div class="eti-toolbar">
    <button type="button" class="eti-slow-toggle" aria-pressed="false">0.3× 慢放</button>
  </div>

  <div class="eti-tabs" role="tablist" aria-label="频道导航">
    <button role="tab" aria-selected="true" class="eti-tab" tabindex="0">
      <span class="eti-label" data-text="关注">关注</span>
    </button>
    <button role="tab" aria-selected="false" class="eti-tab" tabindex="-1">
      <span class="eti-label" data-text="推荐">推荐</span>
    </button>
    <button role="tab" aria-selected="false" class="eti-tab" tabindex="-1">
      <span class="eti-label" data-text="新品首发">新品首发</span>
    </button>
    <button role="tab" aria-selected="false" class="eti-tab" tabindex="-1">
      <span class="eti-label" data-text="家居">家居</span>
    </button>
    <button role="tab" aria-selected="false" class="eti-tab" tabindex="-1">
      <span class="eti-label" data-text="数码测评">数码测评</span>
    </button>
    <span class="eti-bar" aria-hidden="true"></span>
  </div>

  <div class="eti-pages">
    <div class="eti-track">
      <section class="eti-page">关注动态:订阅作者的近况与更新摘要</section>
      <section class="eti-page" inert>精选推荐:按兴趣匹配的今日图文与灵感合集</section>
      <section class="eti-page" inert>新品首发:本周上线的设计工具与硬件新品</section>
      <section class="eti-page" inert>家居灵感:原木色调与小户型桌面收纳方案</section>
      <section class="eti-page" inert>数码测评:续航实测与键盘手感横向对比</section>
    </div>
  </div>
</div>

同属「点击与反馈」的其他动效

查看全部 86 个动效 →

本次更新仅弹窗提醒一次 · 可随时在历史公告回看