示例工程 48-project-shell

48-project-shell/demo-02-toc/index.html

html · 2.5 KB

运行:页内目录演示

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>页内目录演示</title>
    <style>
      * { box-sizing: border-box; }
      html { scroll-behavior: smooth; }
      body { margin: 0; background: #f8fafc; color: #0f172a; font-family: system-ui, sans-serif; line-height: 1.75; }
      .layout { display: grid; grid-template-columns: minmax(0, 1fr) 220px; gap: 28px; max-width: 900px; margin: 0 auto; padding: 24px 20px 60px; }
      h1 { margin: 0 0 10px; font-size: 30px; }
      h2 { margin: 30px 0 8px; font-size: 20px; scroll-margin-top: 16px; }
      p { margin: 0 0 12px; color: #334155; }
      .toc { position: sticky; top: 16px; align-self: start; font-size: 13px; }
      .toc h2 { margin: 0 0 6px; font-size: 13px; letter-spacing: 0.08em; color: #64748b; scroll-margin-top: 0; }
      .toc ol { margin: 0; padding-left: 18px; }
      .toc a { color: #475569; text-decoration: none; }
      .toc a:hover { color: #2563eb; }
      .mobile { display: none; margin: 12px 0; }
      .mobile summary { cursor: pointer; font-weight: 600; }
      .block { height: 140px; padding: 12px; border: 1px dashed #cbd5e1; border-radius: 8px; background: #fff; color: #64748b; font-size: 13px; }
      code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, monospace; }
      @media (max-width: 760px) { .layout { grid-template-columns: 1fr; } .toc { display: none; } .mobile { display: block; } }
    </style>
  </head>
  <body>
    <div class="layout">
      <main>
        <h1>页内目录</h1>
        <p>目录链接到标题 id,标题设置 <code>scroll-margin-top</code>,跳转后不被固定头部遮住。</p>

        <details class="mobile">
          <summary>本页目录</summary>
          <ol>
            <li><a href="#a">第一节</a></li>
            <li><a href="#b">第二节</a></li>
            <li><a href="#c">第三节</a></li>
          </ol>
        </details>

        <h2 id="a">第一节</h2>
        <div class="block">内容占位</div>
        <h2 id="b">第二节</h2>
        <div class="block">内容占位</div>
        <h2 id="c">第三节</h2>
        <div class="block">内容占位</div>
      </main>

      <aside class="toc" aria-labelledby="toc-title">
        <h2 id="toc-title">本页目录</h2>
        <ol>
          <li><a href="#a">第一节</a></li>
          <li><a href="#b">第二节</a></li>
          <li><a href="#c">第三节</a></li>
        </ol>
      </aside>
    </div>
  </body>
</html>