无障碍考量

CMS 驱动网站的无障碍,关键在于恰当地建模内容、创建无障碍的模板,以及编写无障碍的内容,并始终考虑可读性与无障碍准则。

Wagtail 通常把内容建模与前端的标记交给开发者掌控,但仍有一些区域需要注意,也有办法帮助作者了解可读性的最佳实践。 请注意,构建无障碍网站涉及的内容远多于本文所述 —— 更多信息见我们的无障碍资源列表。

内容建模

在为站点定义模型时,以下这些方面值得特别留意:

图片的替代文本

任何使用图片的地方,内容编辑者都应能把图片标记为装饰性图片,或提供符合上下文的文本替代。我们富文本编辑器中的图片嵌入支持这一行为。Wagtail 6.3 新增了 ImageBlock,为 StreamField 中的图片提供同样的行为。

Wagtail 6.3 还在 Wagtail 图片模型以及继承 wagtail.images.models.AbstractImage 的自定义图片模型上新增了可选的 description 字段。在富文本中插入图片或使用 ImageBlock 时,该字段中的文本会作为默认的替代文本提供。如果 description 字段为空,则改用 title 字段。如果你想定制这一行为,请在图片模型中覆盖 default_alt_text 属性。

备注

重要考量

  • 替代文本应基于图片展示的上下文来撰写。

  • 指定替代文本字段时,务必设为可选,好让编辑者可以选择不为装饰性图片写任何替代文本。同一张图片在某些场景下可能是装饰性的,在另一些场景下则不是。例如页面列表中的缩略图通常可视为装饰性图片。

  • 如果替代文本的内容已是页面其它部分的内容,理想情况下图片不应重复同样的内容。

  • 花时间为这些字段提供恰当的 help_text 指引。例如链接到关于替代文本的既有资源。

嵌入内容的标题

缺少嵌入标题是 Wagtail 网站无障碍审计中常见的失败项。有些情况下,Wagtail 嵌入的 iframe 没有设置 title 属性。这通常是 OEmbed 提供方的问题。 这对屏幕阅读器用户非常不利,他们依赖标题来理解嵌入的是什么内容,以及是否需要与之交互。

如果你的网站依赖缺少标题的嵌入内容,请务必做到以下之一:

  • 把 OEmbed 的 title 字段添加为 iframe 的 title。

  • 为嵌入内容添加一个自定义的必填 Title 字段,并把它作为 iframe 的 title。

可用的标题层级

Wagtail 让开发者可以非常容易地通过富文本特性或自定义 StreamField 区块,控制任何给定内容可用的标题层级。 这两种情况下,都要花时间限制可用的标题层级,使页面的文档大纲更有可能合乎逻辑且连贯。可以考虑采用下列限制:

  • 在富文本中禁用 h1。每页应当只有一个 h1 标签,通常对应页面的 title。

  • 页面主体内容的标题层级限制到 h2。只有在确有必要时才加 h3。一般规则下避免其它层级。

  • 对于在页面特定区域展示的内容,标题层级限制为该区域主标题的直接下一级。

如果通过 StreamField 管理标题,请确保在那里也施加同样的限制。

富文本中的粗体与斜体格式

默认情况下,Wagtail 把粗体存为 b 标签,斜体存为 i(#4665)。虽然这些标签并不总是具备正确的语义(strong 和 em 更为通用),但对屏幕阅读器用户来说后果不大,因为默认情况下屏幕阅读器不会根据强调程度以不同方式播报内容。

如果你在意这一点,可以通过富文本格式转换器改变保存内容时使用的标签。未来,富文本重写处理器也应支持在不改变存储格式的前提下做到这一点(#4223)。

TableBlock

屏幕阅读器会使用行标题与列标题来播报表格的每个单元格的上下文。请鼓励编辑者为其表格恰当地设置行标题和/或列标题。

始终添加标题(Caption),好让浏览站点表格的屏幕阅读器用户在表格内容被朗读之前先了解表格的整体内容。

模板中的无障碍

以下是一些常见坑点,注意它们可以让站点模板尽可能无障碍。

模板中的替代文本

见上文的内容建模小节。此外,请务必定制图片的替代文本,可以把它设为相关字段,或对装饰性图片、以及替代文本会重复其它内容的图片设为空字符串。 即使图片的替代文本直接来自图片模型,你仍需要判断在该图片的具体使用场景中是否应有替代文本。例如,在列表中应避免让替代文本只是重复列表条目的标题。

空的标题标签

在富文本和自定义 StreamField 区块中,编辑者很容易创建了标题区块却没有填入任何内容。内置内容检查器会高亮空的标题,方便编辑者发现并修正。如果你需要更严格的强制约束:

  • 为这些字段添加校验规则,确保页面无法带着空标题保存,例如使用 StreamField 的 CharBlock,它默认就是必填的。

  • 考虑为富文本字段添加类似的校验规则。

另外,你也可以用 CSS 隐藏空的标题区块:

h1:empty,
h2:empty,
h3:empty,
h4:empty,
h5:empty,
h6:empty {
    display: none;
}

表单

表单构建器使用 Django 的表单 API。以下是模板中表单相关的考量:

  • 避免使用 as_table、as_ul、as_p 这类渲染辅助方法,它们可能让屏幕阅读器用户更难浏览表单,或引发 HTML 校验问题。

  • 确保在视觉上区分必填与可选字段。

  • 花时间把相关字段归入 fieldset 并配上恰当的 legend,尤其是单选按钮和复选框。

  • 如果相关,请使用恰当的 autocomplete 和 autocapitalize 属性。

  • 对于 Date 和 Datetime 字段,确保显示预期格式或示例值(见 Django ticket #32340)。或使用 input type="date"。

  • 对于 Number 字段,请考虑 input type="number" 是否真的合适,或者是否存在更好的替代方案,例如 inputmode。

请务必用辅助技术测试表单的实现,并查阅 W3C 关于无障碍表单开发的官方指引以获取更多信息。

编写无障碍的内容

有许多内置工具和额外资源可以帮助创建无障碍内容。

内置内容检查器

Wagtail 在用户栏和支持预览的编辑视图中内置了一个内容检查器。该检查器可以帮助作者遵循 WCAG 等最佳实践与无障碍标准,创建更无障碍的网站。

该检查器基于 Axe 测试引擎,会扫描已加载的页面以查找错误。

默认情况下,该检查器包含下列规则,用于发现所编写内容中的常见问题:

  • button-name:<button> 元素必须始终有文本标签。

  • empty-heading:该规则检查没有文本内容的标题。空标题会让屏幕阅读器用户困惑,应避免出现。

  • empty-table-header:表格表头文本不应为空

  • frame-title:<iframe> 元素必须始终有文本标签。

  • heading-order:该规则检查不正确的标题顺序。标题应按合乎逻辑且一致的方式排列,主标题(h1)后面跟副标题(h2、h3 等)。

  • input-button-name:<input> 按钮元素必须始终有文本标签。

  • link-name:<a> 链接元素必须始终有文本标签。

  • p-as-heading:该规则检查被样式化为标题的段落。段落不应被样式化为标题,因为这对依赖标题导航内容的用户没有帮助。

  • alt-text-quality:一条自定义规则,确保图片替代文本不含文件扩展名、下划线之类的反模式。

  • empty-meta-description:一条侧重 SEO 的规则,确保 meta description 标签存在时总是包含内容。

要定制检查器的运行方式(例如测试哪些规则),你可以定义 ContentCheckerItem 的自定义子类并随意覆盖其中的属性。然后通过 construct_wagtail_userbar hook,把默认 ContentCheckerItem 的实例替换为你自定义类的实例。

例如,Axe 的 p-as-heading 规则会综合字重、字号和斜体来判断某个段落在视觉上是否充当标题。视你的标题样式而定,你可能希望 Axe 只依据字重就把短小的粗体段落标记为潜在标题。

from wagtail.admin.userbar import ContentCheckerItem


class CustomContentCheckerItem(ContentCheckerItem):
    def get_axe_custom_checks(self, request):
        checks = super().get_axe_custom_checks(request)
        # 仅依据与周围内容的字重对比来标记形似标题的段落。
        checks.append(
            {
                "id": "p-as-heading",
                "options": {
                    "margins": [
                        {"weight": 150},
                    ],
                    "passLength": 1,
                    "failLength": 0.5,
                },
            },
        )
        return checks


@hooks.register("construct_wagtail_userbar")
def replace_userbar_content_checker(request, items, page):
    items[:] = [
        CustomContentCheckerItem(in_editor=item.in_editor)
        if isinstance(item, ContentCheckerItem)
        else item
        for item in items
    ]

自定义内容检查

你也可以实现自定义检查。这在需要强制执行更高级的无障碍检查,或与无障碍无关的其它最佳实践时很有用。这需要通过 hook 进行配置,并通过 window.wagtail.userbar.registerCheck API 注册任何客户端检查的求值逻辑。

首先,我们要配置自定义的 ContentCheckerItem 来添加这项检查。我们需要:

  • 通过 get_axe_custom_checks 添加一项新的 Axe 检查。

  • 通过 get_axe_custom_rules 创建一条使用该检查的新规则。

  • 通过 get_axe_messages 为该规则提供有帮助的内容。

  • 配置我们的用户栏条目,加载包含该检查的 JS 文件。

# wagtail_hooks.py
from django.utils.translation import gettext_lazy as _
from wagtail.admin.userbar import ContentCheckerItem

class CustomContentCheckerItem(ContentCheckerItem):
    def get_axe_custom_checks(self, request):
        checks = super().get_axe_custom_checks(request)
        return checks + [
            {
                "id": "check-element-text",
                "options": {"antipattern": "^(click here|click this|go|here|this|start|more|learn more)$"},
            },
        ]

    def get_axe_custom_rules(self, request):
        rules = super().get_axe_custom_rules(request)
        return rules + [
            {
                "id": "link-text-quality",
                "impact": "serious",
                "selector": "a[href]",
                "tags": ["best-practice"],
                "any": ["check-element-text"],
                "enabled": True,
            },
        ]

    def get_axe_messages(self, request):
        messages = super().get_axe_messages(request)
        return {
            **messages,
            "link-text-quality": {
                "error_name": _("Link does not have descriptive text"),
                "help_text": _("Link text should describe the link destination."),
            },
        }
    
   class Media:
        js = (
            "js/custom-checks.js",
        )


@hooks.register('construct_wagtail_userbar')
def replace_userbar_content_checker(request, items, page):
    items[:] = [
        CustomContentCheckerItem(in_editor=item.in_editor)
        if isinstance(item, ContentCheckerItem) else item
        for item in items
    ]

对于自定义检查,id 是必填的,且应唯一。options 是可选的,可用于向检查函数传递额外参数。这里我们配置要标记哪些链接文本模式。对于自定义规则,selector 定义了它会对所有锚元素上的元素文本进行标记,无论它们出现在页面何处。该规则的 any 列出了它会运行的所有检查。

在 custom-checks.js 文件中,我们实现用于评估页面内容并注册它的 JavaScript 函数。registerCheck 方法接受两个参数:检查标识符和求值函数。

// static/js/custom-checks.js

/**
 * 检查元素文本是否匹配某个反模式。
 * @param {HTMLElement} node
 * @param {Object} options
 * @param {string} options.antipattern 用于匹配元素文本的正则模式。
 * @returns {boolean} 元素文本不匹配该模式时返回 True,否则返回 false。
 */
const checkElementText = (node, options) => {
    const antipattern = new RegExp(options.antipattern, 'i');
    return !antipattern.test(node.textContent.trim());
};

window.wagtail.userbar.registerCheck('check-element-text', checkElementText);

环境相关的检查

你在生产环境中运行的检查应限于内容编辑者自己能修正的问题;对他们无法控制的事项发出警告,只会让他们学会忽略所有警告。不过,在开发环境中运行额外的检查可能对你很有用。

from django.conf import settings
from wagtail.admin.userbar import ContentCheckerItem


class CustomContentCheckerItem(ContentCheckerItem):
    # 在开发环境中运行所有带这些标签的 Axe 规则
    axe_rules_in_dev = [
        "wcag2a",
        "wcag2aa",
        "wcag2aaa",
        "wcag21a",
        "wcag21aa",
        "wcag22aa",
        "best-practice",
    ]
    # 但排除 color-contrast-enhanced 规则
    axe_rules = {
        "color-contrast-enhanced": {"enabled": False},
    }

    def get_axe_run_only(self, request):
        if settings.DEBUG:
            return self.axe_rules_in_dev
        else:
            # 在生产环境中,只运行 Wagtail 针对所编写内容的默认无障碍规则
            return self.axe_run_only


@hooks.register("construct_wagtail_userbar")
def replace_userbar_content_checker(request, items, page):
    items[:] = [
        CustomContentCheckerItem(in_editor=item.in_editor)
        if isinstance(item, ContentCheckerItem)
        else item
        for item in items
    ]

ContentCheckerItem 类接受一个 in_editor 参数,在页面编辑器内实例化时它会被设为 True。这让你可以依据 Axe 是在页面编辑器中运行还是在站点前端运行来定制 Axe 配置。例如,当无障碍检查器加载在无头前端中时,改变 Axe 规范中的 allowedOrigins 属性以允许跨域 iframe 通信。

ContentCheckerItem 参考

下面是 ContentCheckerItem 类的参考文档:

class wagtail.admin.userbar.ContentCheckerItem(in_editor=False)

A userbar item that runs the content checker.

in_editor

Whether the content checker is being run in the page editor.

axe_include = ['body']

A list of CSS selector(s) to test specific parts of the page. For more details, see Axe documentation.

axe_exclude = []

A list of CSS selector(s) to exclude specific parts of the page from testing. For more details, see Axe documentation.

axe_run_only

A list of axe-core tags or a list of axe-core rule IDs (not a mix of both). Setting this to a falsy value (e.g. None) will omit the runOnly option and make Axe run with all non-experimental rules enabled.

axe_rules = {}

A dictionary that maps axe-core rule IDs to a dictionary of rule options, commonly in the format of {"enabled": True/False}. This can be used in conjunction with axe_run_only to enable or disable specific rules. For more details, see Axe documentation.

axe_custom_rules

For more details, see Axe documentation.

axe_custom_checks

A list to add custom Axe checks or override their properties. Should be used in conjunction with axe_custom_rules. For more details, see Axe documentation.

axe_messages

A dictionary that maps axe-core rule IDs to custom translatable strings to use as the error messages. If an enabled rule does not exist in this dictionary, Axe's error message for the rule will be used as fallback.

The above attributes can also be overridden via the following methods to allow per-request customization. When overriding these methods, be mindful of the mutability of the class attributes above. To avoid unexpected behavior, you should always return a new object instead of modifying the attributes directly in the methods.

get_axe_include(request)
get_axe_exclude(request)
get_axe_run_only(request)
get_axe_rules(request)
get_axe_custom_rules(request)
get_axe_custom_checks(request)
get_axe_messages(request)

For more advanced customization, you can also override the following methods:

get_axe_context(request)

Returns the context object to be passed as the context parameter for axe.run.

get_axe_options(request)

Returns the options object to be passed as the options parameter for axe.run.

get_axe_spec(request)

Returns spec for Axe, including custom rules and custom checks

wagtail-accessibility

wagtail-accessibility 是一个第三方包,它把 tota11y 加到 Wagtail 的预览中。 这让作者可以轻松运行基本的无障碍检查 —— 校验页面的标题大纲或链接文本。

help_text 与 HelpPanel

偶尔使用 Wagtail 的用户可能不熟悉你的站点内容规范,或网络写作的最佳实践。请使用字段的 help_text 和 HelpPanel(见面板类型)。

可读性

可读性是无障碍的基础。改善文本内容的方法之一是设定清晰的阅读水平/阅读年龄目标,可以用 wagtail-readinglevel 以分数的形式在富文本字段中展示。

prefers-reduced-motion

有些用户(例如患有前庭功能障碍的人)可能更喜欢站点呈现更静态的版本。你可以通过在 CSS 中使用 prefers-reduced-motion 媒体查询来尊重这一偏好。

@media (prefers-reduced-motion) {
    /* 当用户设备设置为减少动态效果时应用的样式 */
    /* 例如,禁用动画 */
    * {
        animation: none !important;
        transition: none !important;
    }
}

注意,prefers-reduced-motion 只对在操作系统或浏览器中启用了该设置的用户生效。Chrome、Safari 和 Firefox 都支持这项特性。关于减少动态效果的更多信息,见 MDN Web 文档。

无障碍资源

我们聚焦于 Wagtail 网站特有的考量,但无障碍涉及的内容远不止这些。以下是一些值得进一步学习的资源,既面向开发者,也面向设计师和作者: