示例工程 37-keyboard-focus

37-keyboard-focus/demo-01-tabindex/index.html

html · 1.9 KB

运行:tabindex 演示

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

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>tabindex 演示</title>
    <style>
      body { margin: 0; padding: 32px; background: #f8fafc; color: #0f172a; font-family: system-ui, sans-serif; line-height: 1.7; }
      .box { max-width: 720px; margin-bottom: 16px; padding: 18px; border: 1px solid #e2e8f0; border-radius: 12px; background: #fff; }
      h1 { margin: 0 0 16px; font-size: 28px; }
      h2 { margin: 0 0 8px; font-size: 17px; }
      p { margin: 0 0 10px; color: #334155; }
      :focus-visible { outline: 3px solid #2563eb; outline-offset: 2px; }
      a, button { color: #2563eb; }
      button { padding: 7px 12px; border: 1px solid #2563eb; border-radius: 6px; background: #fff; font: inherit; }
      .card { padding: 12px; border: 1px solid #e2e8f0; border-radius: 8px; }
      code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, monospace; }
      pre { margin: 8px 0 0; padding: 12px; overflow-x: auto; border-radius: 8px; background: #0f172a; color: #e2e8f0; font-size: 12px; }
    </style>
  </head>
  <body>
    <h1>tabindex</h1>

    <div class="box">
      <h2>自然顺序</h2>
      <p><a href="#top">链接一</a> → <button type="button">按钮</button> → <a href="#top">链接二</a></p>
      <p>按 Tab 依次经过它们。</p>
    </div>

    <div class="box">
      <h2>0 与 -1</h2>
      <div class="card" tabindex="0">tabindex=0:加入 Tab 顺序</div>
      <div class="card" tabindex="-1">tabindex=-1:只能脚本聚焦</div>
      <p><code>-1</code> 适合跳转目标、对话框、错误摘要。</p>
    </div>

    <div class="box">
      <h2>不要用正数</h2>
      <pre>&lt;button tabindex="2"&gt;…&lt;/button&gt;  <!-- 打乱顺序 --></pre>
      <p>正数 tabindex 会让元素跳到自然顺序之前,难以维护。</p>
    </div>
  </body>
</html>