大多数为仅屏幕阅读器元素提供 css 类的指南建议如下所示(来自 https://medium.com/web-dev-survey-from-kyoto/the-visually-hidden-technique-303f8e2bd409):
.visually-hidden {
/* Contain text within 1px box */
height: 1px;
overflow: hidden;
width: 1px;
/* Keep the layout */
position: absolute;
/* Remove any visible trace (e.g. background color) */
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
clip-path: inset(50%); /* browsers in the future */
/* Prevent the screen reader to skip spaces between words */
white-space: nowrap;
}
但是,Edge 的“大声朗读”功能不会读取视觉隐藏元素内的文本。
例如,Edge Read Aloud 将仅读取“Lucy Bob”,给出以下 html:
<p>
Lucy
<span style="height: 1px; width: 1px; position: absolute; clip: rect(1px, 1px, 1px, 1px); clip-path: inset(50%); white-space: nowrap; overflow: hidden">and</span>
Bob
</p>
删除
overflow
属性将使 Edge 读取“Lucy 和 Bob”,但当隐藏元素足够长时会导致水平滚动条,例如:
<p>
Lucy
<span style="height: 1px; width: 1px; position: absolute; clip: rect(1px, 1px, 1px, 1px); clip-path: inset(50%); white-space: nowrap">and Mary and Sue and Jemima and Zog and Olivia and Yog-Sothoth and foo and Ashurbanipal and Tutankhamun and Kamehameha the Great and Felipe Juan Pablo Alfonso de Todos los Santos de Borbón y Grecia and Mary and Sue and Jemima and Zog and Olivia and Yog-Sothoth and foo and Ashurbanipal and Tutankhamun and Kamehameha the Great and Felipe Juan Pablo Alfonso de Todos los Santos de Borbón y Grecia</span>
Bob
</p>
将导致屏幕上出现水平滚动条。
有没有一种解决方案,不会插入水平滚动条,但会被 Edge 的 Read Aloud 功能读取?
似乎只有将元素移动到最左边位置的解决方案在 Edge 中才有效。您可以参考下面的代码示例,Edge 会读取隐藏元素:
.screenreader {
position: absolute;
left: -9999px;
}
<p>
Lucy
<span class="screenreader">and Mary and Sue and Jemima and Zog and Olivia and Yog-Sothoth and foo and Ashurbanipal and Tutankhamun and Kamehameha the Great and Felipe Juan Pablo Alfonso de Todos los Santos de Borbón y Grecia and Mary and Sue and Jemima and Zog and Olivia and Yog-Sothoth and foo and Ashurbanipal and Tutankhamun and Kamehameha the Great and Felipe Juan Pablo Alfonso de Todos los Santos de Borbón y Grecia</span> Bob
</p>