front-end-interview-handbook/packages/quiz/questions/what-are-the-different-ways.../zh-CN.mdx

75 lines
2.4 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 有哪些不同的方法可以隐藏内容(使其仅对屏幕阅读器可用)?
---
这些技术与可访问性 (a11y) 相关。
## 小/零尺寸
`width: 1px; height: 1px` 并结合使用 CSS clip 使元素在屏幕上几乎不占用任何空间。
不建议使用 `width: 0; height; 0`,因为搜索引擎可能会因此受到惩罚,认为它有恶意意图,例如关键词堆砌。
## 绝对定位
`position: absolute; left: -99999px` 将把元素定位到屏幕之外。但是,根据 [WebAIM 的文章](https://webaim.org/techniques/css/invisiblecontent/)
> 可导航元素(例如链接和表单控件)不应隐藏在屏幕外。有视觉的用户仍然可以使用键盘导航它们,但除非对它们进行样式设置以使其在接收到键盘焦点时可见,否则他们将看不到它们。
仅当您的内容仅包含文本时才使用此方法。
## 文本缩进
`text-indent: -9999px`。这仅适用于 `block` 元素中的文本。与上面的绝对定位技术类似,给定此样式的可聚焦元素仍然可以聚焦,这会给使用键盘导航的视觉用户造成混淆。
## 错误的方法
以下方法是错误的,因为它们会向用户 **和** 屏幕阅读器隐藏内容,如果目的是仅向屏幕阅读器公开内容,则这是不正确的。
* `display: none`
* `visibility: hidden`
* `hidden` 属性
## 实际应用中的技术
理想情况下,建议结合上述方法,以确保它在所有浏览器中都能正常工作。
建议您使用成熟 CSS 框架中的以下方法之一,而不是实现您自己的从渲染树和 a11y 树中删除元素的方法,这些方法已经在许多网站上经过了实战测试。
### Tailwind CSS
```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-width: 0;
}
```
### Bootstrap CSS
```css
.visually-hidden,
.visually-hidden-focusable:not(:focus):not(:focus-within) {
position: absolute !important;
width: 1px !important;
height: 1px !important;
padding: 0 !important;
margin: -1px !important;
overflow: hidden !important;
clip: rect(0, 0, 0, 0) !important;
white-space: nowrap !important;
border: 0 !important;
}
```
## 参考资料
* [CSS in Action - Invisible Content Just for Screen Reader Users](https://webaim.org/techniques/css/invisiblecontent/)