将 WAI-ARIA 支持添加到 jQuery .toggle() 方法



我想将WAI-ARIA aria-hidden支持与jQuery的.toggle()方法配对。

所以给定<p id="myElement">Hi there</p>

$('#myElement').toggle()将隐藏元素,并设置aria-hidden="true"

<p id="myElement" style="display: none;" aria-hidden="true">Hi there</p>

再次执行相同的$('#myElement').toggle()脚本将显示(切换)元素,并设置(切换)aria-hidden="false"

<p id="myElement" style="display: block" aria-hidden="false">Hi there</p>

我可能想使用该方法的完整功能,也许

类似于
$('#myElement').toggle(
    if ($this.css('display')==='none'){
       $this.prop('aria-hidden', 'true')
    }
    else
    {
            $this.prop('aria-hidden', 'false')
    }
)

扩展.toggle()以切换aria-hidden状态的最高性能解决方案是什么?

简短的回答是没有必要这样做。

可访问技术以一种已经正确隐藏元素的方式支持 CSS 的 display: hidden; 属性。因此,从屏幕阅读器的角度来看,指定aria-hidden="true"是多余的,jQuery的.toggle()方法将display属性设置为hidden。指定aria-hidden="false"(或删除aria-hidden属性)对于 jQuery 的.toggle()方法将display属性设置为 inline 是多余的。

请参阅 https://stackoverflow.com/a/10351673/1430996 和Steve Faulkner的HTML5 Accessibility Chops:隐藏和咏叹调隐藏博客文章(特别是"结果摘要"),以获取更多详细信息。

公认的答案在精神上是正确的,但在细节上存在一些问题:

  1. CSS Display 属性没有"隐藏"值,它应该是"none"。

  2. jQuery .toggle() 在取消隐藏时不会将显示设置为"内联";它会将其设置回空白,这会回退到级联规定的任何值。因此,如果显示的计算值是"块",这就是它返回的值。

最新更新