如何在 Thymeleaf 模板中实现跳过导航链接(skip to content)?
解读
国内政府网站与金融、电商类项目必须通过“无障碍”与“适老化”测评,其中“跳过导航”是硬性指标。
面试官想确认两点:
- 你是否了解 WCAG 2.1 中 2.4.1 Bypass Blocks 条款;
- 你是否能把纯前端做法无缝落地到 Thymeleaf 的模板体系里,而不是“写死”在 HTML。
回答时务必体现“自然模板”理念:静态原型能直接打开,动态后仍符合无障碍规范,且对 SEO 与缓存友好。
知识点
- 自然模板(Natural Template):Thymeleaf 允许 th:* 属性与原生 HTML 共存,浏览器可离线预览。
- 片段(fragment):公共头部、导航、尾部通常抽取为 /fragments/header.html、/fragments/footer.html,用 th:replace 或 th:insert 组合。
- 锚点定位:通过 href="#main" 与对应 id="main" 实现键盘可访问的“跳过”功能。
- 样式隐藏但屏幕阅读器可读:使用官方推荐的 visually-hidden 或 sr-only 类,避免 display:none 被辅助技术忽略。
- Spring Boot 集成:通过 messages.properties 做国际化,保证“跳过导航”四字在中文站显示为中文,在英文站显示为“Skip to main content”。
- 缓存与安全:链接是纯锚点,无参数,无需 CSRF 令牌;片段可被 th:cache 缓存,不影响性能。
答案
步骤一:在公共资源包(src/main/resources/static/css/utility.css)写入官方无障碍样式
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
.sr-only:focus{position:static;width:auto;height:auto;margin:0;clip:auto;white-space:normal}
步骤二:在 messages.properties 写国际化键
skip.link=跳过导航
步骤三:新建 /templates/fragments/a11y.html
<a th:fragment="skip" th:href="${mainTarget}" class="sr-only" th:text="#{skip.link}">跳过导航</a>
步骤四:在基础布局文件 /templates/layout/base.html 中引入
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:fragment="base">
<head th:replace="~{fragments/head :: head}"></head>
<body>
<!-- 1. 跳过导航,必须是 DOM 最前的可聚焦元素 -->
<div th:replace="~{fragments/a11y :: skip(${mainTarget})}"></div>
<!-- 2. 头部导航 -->
<header th:replace="~{fragments/header :: nav}"></header>
<!-- 3. 主内容区,id 与 skip 链接对应 -->
<main id="main" tabindex="-1">
<div layout:fragment="content"></div>
</main>
<footer th:replace="~{fragments/footer :: foot}"></footer>
</body>
</html>
步骤五:业务页面继承布局并只填内容
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout/base}">
<head><title>商品列表</title></head>
<body>
<div layout:fragment="content">
……
</div>
</body>
</html>
关键点
- 使用 th:href="${mainTarget}" 而非写死 #main,保证当主内容区 id 变化时只需改一处。
- 样式类用 sr-only,聚焦时自动显现,符合国内无障碍测评“可见即可达”要求。
- 整个片段无 JavaScript,SEO 与静态原型都能直接打开,满足 Thymeleaf 自然模板理念。
拓展思考
- 多语言站点:除 messages.properties 外,再建 messages_en.properties,Spring Boot 会根据 Accept-Language 自动切换,无需额外编码。
- 动态锚点:若页面通过 AJAX 加载多个 Tab,可把 mainTarget 作为 Model 属性传入,实现“跳过至当前激活的 TabPanel”。
- 自动化测试:在 Selenium 中通过 By.linkText("跳过导航") 定位,验证 Tab 键第一次聚焦即为该链接,确保无障碍链路完整。
- 性能优化:对头部、尾部、skip 片段统一加 th:cache="fragments",在纯展示型页面可把缓存时间设 1h,减少渲染开销。
- 设计协作:UI 走查时让设计师直接打开静态原型,按 Tab 即可看到黄色高亮的“跳过导航”按钮,无需启动后端,减少沟通成本。