禁止所有辅助功能读取占位符文本 API(屏幕 reader)

Disable placeholder text to be read by all accessibility API(screen reader)

有些屏幕 reader 读取占位符值,有些则不读取。有没有一种方法可以为所有屏幕 reader(在 HTML 输入的上下文中)禁用读取占位符值。特别是 IOS 屏幕 reader 读取占位符值,在这种情况下,相同的信息重复了两次。

我想要的是显示屏幕用户的占位符和屏幕 reader 用户的隐藏标签。

编辑:当我问这个问题时,这是第一次处理可访问性,只是为了解决一个问题。在进一步探索中,我发现我们可以只使用隐藏标签并将其与用于属性的输入元素相关联。这里是 w3 文档 link.

如果你真的想发挥创意,理论上你可以使用 JS 来管理占位符属性。它会稍微减慢页面的加载速度,但是您可以在输入获得焦点时删除占位符属性,并在输入失去焦点时重新添加它。这将具有禁用辅助技术的占位符属性的效果(至少在交互表单模式下)。有视力的游客可能不会注意到其中的区别。这是 example in a fiddle。我在 NVDA/Chrome 中进行了测试并且它有效,但我不能代表任何其他 screen-reader/browser 组合。

// on document load, add the placeholder text
document.addEventListener("DOMContentLoaded", function(){
   myInput.setAttribute("placeholder", myPlaceholder)
});

// when receiving focus, remove the placeholder text
myInput.addEventListener('focus', (event) => {
    myInput.removeAttribute("placeholder");
});

// when losing focus, re-add the placeholder text
myInput.addEventListener('blur', (event) => {
   myInput.setAttribute("placeholder", myPlaceholder)
});

正如其他人所说,使用占位符不是使用标签的合适替代品。如果您真的不喜欢标签的外观,可以 position them off-screen or use the clip technique 并继续使用占位符。缺点是一些屏幕阅读器可能会同时阅读标签和占位符,这并不理想,但过度描述总比描述不足好。如果某些内容仅出现在某些 browser/screen-reader 组合中,我个人会同意某些内容被读取两次,并且我的代码在其他方面有效并且符合 WCAG 要求。

根据Understanding Success Criterion 2.5.3: Label in Name

As such, in the absence of any other nearby text string (as described in the preceding list), if an input contains placeholder text, such text may be a candidate for Label in Name. This is supported both through the accessible name calculation (discussed later) and from the practical sense that where a visible label is not otherwise provided, it is likely that a speech-input user may attempt to use the placeholder text value as a means of interacting with the input.

只要您不提供视觉标签,辅助技术(例如语音输入)就会使用占位符文本。禁用输入辅助以向输出辅助提供更多用户体验会适得其反。

当字段为空时,您完全可以使用模拟占位符行为的视觉标签(采取适当的预防措施,使字段在字段填充后可在输入帮助下使用)。

根据我在问题中提到的要求

What I want is to show placeholders for screen users and hidden labels for screen reader users.

最好的方法是添加一个隐藏标签并将输入元素与属性关联到相应的标签。

<label for="search" class="visuallyhidden">Search: </label>
<input type="text" name="search" id="search" placeholder>
<button type="submit">Search</button>
.visuallyhidden {
      border: 0;
      clip: rect(0 0 0 0);
      height: 1px;
      margin: -1px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1px;
    }

此外,您可以简单地将应用样式的标签隐藏为 display: none

<label style={{display: 'none'}} for="search"> Search: </label> 

你可以关注w3.org document。真的很值得看看文档。