第 15 章 · 可访问性、SEO 与安全基础
本章目标:为 academy-demo 补齐 ARIA、语义 HTML、SEO meta,并建立 XSS、CSRF、CSP 的安全认知,使课程门户达到可上线的基础合规水位。
前置:第 1、9、13 章;了解 HTTP 与 Cookie 基础。
15.1 为什么三者要一起学
| 维度 | 受益者 | 失败代价 |
|---|
| 可访问性(a11y) | 视障、键盘用户、临时伤残 | 法律风险、用户流失 |
| SEO | 搜索引擎、自然流量 | 课程页无法被检索 |
| 安全 | 用户数据、品牌信誉 | 账号被盗、挂马 |
行业案例 · 贤紫优选商城:2023 年某营销页因缺少 alt 与对比度不足被无障碍审计通报;同时 meta 缺失导致课程落地页搜索收录率 < 20%。统一模板后收录提升至 85%,客诉下降。
15.2 语义 HTML 回顾
<body>
<a class="skip-link" href="#main">跳到主内容</a>
<header>
<h1>贤紫技术学院</h1>
<nav aria-label="主导航">...</nav>
</header>
<main id="main">
<section aria-labelledby="courses-heading">
<h2 id="courses-heading">前端课程</h2>
...
</section>
</main>
<footer>...</footer>
</body>
| 标签/模式 | 作用 |
|---|
每页一个 h1 | 文档主题明确 |
nav + aria-label | 区分多个导航区 |
main | 跳过重复头尾 |
section + 标题 id | 屏幕阅读器大纲 |
跳过链接(.skip-link):键盘用户 Tab 第一下可直达主内容,验收时必测。
15.3 ARIA 实用子集
ARIA 不替代语义标签,而是补充动态状态。
| 属性 | 用途 | academy-demo 示例 |
|---|
aria-label | 无可见文字的可点击元素 | 图标按钮「收藏」 |
aria-labelledby | 引用可见标题 id | 对话框标题 |
aria-expanded | 折叠是否展开 | 课程大纲手风琴 |
aria-hidden="true" | 对读屏隐藏装饰性图标 | SVG 装饰 |
role="alert" | 即时通知 | 表单错误提示 |
role="status" | 非紧急状态 | 「已保存」 |
<button
type="button"
id="theme-toggle"
aria-label="切换深色模式"
aria-pressed="false"
>
<svg aria-hidden="true">...</svg>
</button>
themeBtn.addEventListener('click', () => {
const dark = document.body.classList.toggle('theme-dark');
themeBtn.setAttribute('aria-pressed', String(dark));
});
15.3.1 焦点管理
| 规则 | 说明 |
|---|
| 可交互元素可 Tab 到达 | 不用 div 冒充按钮 |
| 可见焦点环 | 勿 outline: none 不设替代 |
| 模态打开 | 焦点 trap + 关闭还原 |
| 动态内容 | 重要更新用 role="alert" |
:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
15.4 色彩与对比度
| 要求 | 标准 |
|---|
| 正文对比度 | WCAG AA:至少 4.5:1 |
| 大字号 | 3:1 |
| 不仅靠颜色 | 错误加图标或文字 |
工具:Chrome DevTools → Rendering → Emulate vision deficiencies;或 axe DevTools 插件。
15.5 SEO 基础
15.5.1 必备 meta
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>前端开发入门 · 贤紫技术学院 academy-demo</title>
<meta name="description" content="从零学习 HTML、CSS、JavaScript,含 16 章系统课程与毕业项目。">
<link rel="canonical" href="https://academy.example.com/frontend-web/">
<meta name="robots" content="index, follow">
<!-- Open Graph(分享卡片) -->
<meta property="og:title" content="贤紫技术学院 · 前端课程">
<meta property="og:description" content="系统化的前端入门到实战路径">
<meta property="og:image" content="https://academy.example.com/og-cover.jpg">
<meta property="og:type" content="website">
</head>
| 元素 | 作用 |
|---|
<title> | 搜索结果标题,唯一且描述性 |
description | 摘要,不堆砌关键词 |
canonical | 避免重复 URL 分散权重 |
| 结构化数据 | JSON-LD Course(进阶) |
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Course",
"name": "前端开发入门",
"provider": { "@type": "Organization", "name": "贤紫技术学院" }
}
</script>
15.5.2 内容与链接
- 重要内容在 HTML 中,而非仅 JS 渲染(爬虫能力因引擎而异)
- 语义化标题层级
h1→h2→h3
- 有意义的链接文字:避免「点击这里」
sitemap.xml 与内部链接帮助收录