确保 Angular 项目的可访问性的简单步骤

来源:undefined 2025-01-20 04:43:30 1026

构建更具包容性的应用程序:从可访问性表单开始

在软件开发中,我们常常专注于功能交付,而忽略了可访问性和测试等重要方面(测试将在另一篇文章中详细讨论)。本文将重点探讨可访问性,它不仅仅关乎残障人士,更能提升所有用户的体验。

我最近深入学习了可访问性,并强烈推荐以下免费课程:

学习可访问性:https://www.php.cn/link/25dd30ae03e63faa6b82d5a6a8dadff4 构建更易于访问的 Angular 应用程序:https://www.php.cn/link/fbffdd7e918c7968f26dfa4088cc84ce

为了实践所学,我构建了一个简单的“给圣诞老人的信”表单,它从设计之初就考虑了可访问性,包括清晰的验证和提交成功反馈。

最终成果如下:

构建可访问表单的重要性在于,它能惠及更多用户,包括视障、肢体障碍、或暂时受限的用户。

我首先使用了语义化的 HTML 元素(如

、ain> 和 ),并通过标题层级(

)组织内容。这有助于屏幕阅读器正确解析页面,并提升 SEO。

示例代码片段:

1

2

3

<header><h1>写信给圣诞老人</h1></header>

<main><h2>填写表单</h2></main>

<footer></footer>

登录后复制

表单不仅仅是输入框和标签的堆砌,更需要恰当的验证和错误消息提示。 我使用了 aria-live 属性来确保屏幕阅读器能及时获取通知,同时为视觉用户提供清晰的视觉反馈,避免不必要的打扰。

role="alert" 用于关键错误消息,role="status" 用于非关键更新。

1

2

3

<div class="error" role="alert">

<p>姓名为必填项。</p>

</div>

登录后复制

aria-live="polite" 则会在屏幕阅读器空闲时宣布内容,适合用于提交成功等通知:

1

2

3

4

5

@if (messagesent) {

<div aria-live="polite" class="notifications" role="status">

<p>{{ message }}</p>

</div>

}

登录后复制

对于仅供屏幕阅读器访问的内容,可以使用 .visually-hidden 类隐藏其视觉显示:

1

2

3

4

5

6

7

8

9

10

11

.visually-hidden {

position: absolute;

width: 1px;

height: 1px;

padding: 0;

margin: -1px;

overflow: hidden;

clip: rect(0, 0, 0, 0);

white-space: nowrap;

border: 0;

}

登录后复制

示例代码片段:

1

2

<span class="visually-hidden">错误:</span>

<p>姓名为必填项。</p>

登录后复制

此外,确保足够的颜色对比度至关重要。可以使用颜色对比度检查器扩展来辅助。

示例代码片段:

1

2

3

4

input.ng-invalid.ng-touched {

border-color: #e74c3c;

background-color: #fdecea;

}

登录后复制

为了保证代码的可访问性,我使用了 ESLint,并添加了可访问性规则,例如 accessibility-label-has-linked-control 和 accessibility-table-scope。

安装 ESLint:

1

ng add @angular-eslint/schematics

登录后复制

ESLint 配置文件 (.eslintrc.json) 中添加可访问性规则:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

{

"overrides": [

{

"files": ["*.component.html"],

"extends": ["plugin:@angular-eslint/template/recommended"],

"rules": {

"@angular-eslint/template/accessibility-elements-content": "error",

"@angular-eslint/template/accessibility-valid-aria": "error",

"@angular-eslint/template/accessibility-label-has-associated-control": "warn",

"@angular-eslint/template/accessibility-table-scope": "error",

"@angular-eslint/template/accessibility-role-supports-aria": "warn",

"@angular-eslint/template/accessibility-click-events-have-key-events": "warn",

"@angular-eslint/template/accessibility-no-positive-tabindex": "error",

"@angular-eslint/template/accessibility-media-has-caption": "warn",

"@angular-eslint/template/accessibility-valid-tabindex": "error",

"@angular-eslint/template/accessibility-input-label": "warn",

"@angular-eslint/template/accessibility-role-has-required-aria": "error"

}

}

]

}

登录后复制

运行 npm run lint 进行代码检查。

总结

在构建应用程序时,请务必记住这些可访问性技巧,从而创建更包容、更易于使用的产品,让所有用户都能获得良好的体验。

以上就是确保 Angular 项目的可访问性的简单步骤的详细内容,更多请关注php中文网其它相关文章!

最新文章