示例工程 37-keyboard-focus
37-keyboard-focus/demo-02-dialog-focus/index.html
点击「运行示例」后,左侧显示源码、右侧显示运行结果;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>
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; }
button { padding: 7px 12px; border: 1px solid #2563eb; border-radius: 6px; background: #2563eb; color: #fff; font: inherit; }
button.secondary { background: #fff; color: #334155; border-color: #cbd5e1; }
.toolbar { display: flex; gap: 6px; padding: 6px; border: 1px solid #e2e8f0; border-radius: 8px; }
.toolbar button { background: #fff; color: #334155; border-color: #cbd5e1; }
dialog { width: min(92vw, 380px); padding: 18px; border: 1px solid #cbd5e1; border-radius: 10px; }
dialog::backdrop { background: rgb(15 23 42 / 0.45); }
dialog .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 12px; }
code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, monospace; }
</style>
</head>
<body>
<h1>焦点管理</h1>
<div class="box">
<h2>对话框</h2>
<dialog open aria-labelledby="title" closedby="any">
<h2 id="title">确认删除?</h2>
<p>删除后无法恢复。</p>
<form method="dialog" class="actions">
<button type="submit" class="secondary" autofocus>取消</button>
<button type="submit" value="delete">删除</button>
</form>
</dialog>
<p>打开时焦点进入对话框,初始焦点在「取消」。</p>
</div>
<div class="box">
<h2>Roving tabindex</h2>
<div class="toolbar" role="toolbar" aria-label="对齐方式">
<button type="button" tabindex="0">左对齐</button>
<button type="button" tabindex="-1">居中</button>
<button type="button" tabindex="-1">右对齐</button>
</div>
<p>整组只占一个 Tab 位,方向键在组内移动。</p>
</div>
</body>
</html>