如何让屏幕reader宣布额外的文字

How to let screen reader to announce extra text

在下面的简单 html 代码中,当屏幕 reader(NVDA,mac 上的 VoiceOver)打开时。

当我在输入框中tab时,它会提示This is the test label(在网页上可见)

我想让屏幕 reader 宣布一些额外的事情,例如 if you type something, more fields will appear。 (隐藏在网页上)

想知道如何实现吗?

<html>
  <head>
    test
  </head>
  <body>
    <label class="large-label" for="your-name">
      This is the test label
    </label>
    <input id="your-name" name="your-name" type="text" />
  </body>
</html>

视觉隐藏文本

您想要在视觉上隐藏/屏幕 reader 仅文本。这可以通过位于下面代码段中的 CSS class 然后将 class 应用于标签中的 <span> 来实现。

它将在 reader 屏幕上宣布,但不可见。

.visually-hidden { 
    border: 0;
    padding: 0;
    margin: 0;
    position: absolute !important;
    height: 1px; 
    width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 - a 0 height clip, off to the bottom right of the visible 1px box */
    clip: rect(1px, 1px, 1px, 1px); /*maybe deprecated but we need to support legacy browsers */
    clip-path: inset(50%); /*modern browsers, clip-path works inwards from each corner*/
    white-space: nowrap; /* added line to stop words getting smushed together (as they go onto seperate lines and some screen readers do not understand line feeds as a space */
}
    <label class="large-label" for="your-name">
      This is the test label <span class="visually-hidden">if you type something, more fields will appear</span>
    </label>
    <input id="your-name" name="your-name" type="text" />

更好的方法

在这种情况下,我会质疑这是否应该是视觉上隐藏的文本。

以“如果您键入内容,将出现更多字段”为例,这是对每个人都有用的信息。它对有认知障碍或焦虑症的人特别有用,因为关于变化的预警有助于他们不感到困惑/为变化做好准备,所以这并不意外。

我建议在表格的开头或特定输入的上方设置一个说明部分,向所有人解释这一点。

然后我们可以 link 使用 aria-labelledby="id1 id2" 输入标签和输入指令,并为标签和指令提供 ID。

您必须保留标签上的 for="" 作为备份/以便标签正确地 link 编辑到输入中,允许您在需要时单击标签以聚焦输入。

下面是一个粗略的示例,您必须根据自己的判断来判断什么适用于您的用例,但它应该会给您一些想法。

#hint{
 width: 90%;
 padding: 5%;
 background-color: #333;
 color: #fff;
 font-size: 1.3rem;
}
<p id="hint">If you type something, more fields will appear</p>

<label class="large-label" for="your-name" id="your-name-label">
      This is the test label
 </label>   
    <input id="your-name" name="your-name" type="text" aria-labelledby="your-name-label hint"/>