示例工程 24-labels-errors
24-labels-errors/demo-02-errors/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; }
label { display: block; margin: 8px 0 4px; font-size: 14px; }
input { width: 100%; max-width: 360px; padding: 7px 9px; border: 1px solid #cbd5e1; border-radius: 6px; font: inherit; }
input[aria-invalid="true"] { border-color: #b91c1c; }
.error { margin: 4px 0 0; color: #b91c1c; font-size: 13px; }
.error::before { content: "错误:"; font-weight: 600; }
.summary { margin: 0 0 14px; padding: 10px 12px; border: 1px solid #fecaca; border-left: 4px solid #b91c1c; border-radius: 6px; background: #fef2f2; color: #7f1d1d; font-size: 14px; }
.summary a { color: #7f1d1d; }
.help { color: #64748b; font-size: 13px; }
</style>
</head>
<body>
<h1>错误提示</h1>
<div class="box">
<h2>错误摘要</h2>
<div class="summary" role="alert">
<p>提交时发现 2 个问题:</p>
<ul>
<li><a href="#email">邮箱:请输入有效的邮箱地址。</a></li>
<li><a href="#password">密码:至少 8 个字符。</a></li>
</ul>
</div>
</div>
<div class="box">
<h2>字段级错误</h2>
<label for="email">邮箱</label>
<input id="email" name="email" type="email" aria-invalid="true" aria-describedby="email-error" />
<p class="error" id="email-error">请输入有效的邮箱地址。</p>
<label for="password">密码</label>
<input id="password" name="password" type="password" aria-invalid="true" aria-describedby="password-help password-error" />
<p class="help" id="password-help">至少 8 个字符。</p>
<p class="error" id="password-error">密码太短。</p>
</div>
<div class="box">
<h2>为什么这样写</h2>
<p>摘要让用户知道有几个错误,字段级提示告诉用户怎么改。</p>
<p>aria-invalid 与 aria-describedby 让读屏也能读到错误。</p>
</div>
</body>
</html>