正文
tabIndex-bootstrap中Get到的
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
网页键盘的无障碍访问性
其实加了这个,可以控制Tab键切换的顺序,聚焦等
这个属性,任何标签都可以添加,没有兼容性限制,属性值的范围:0-32767
当一个元素设置
tabindex
属性值为
-1
的时候,元素会变得
focusable
,所谓
focusable
指的是元素可以被鼠标或者JS
focus
,在Chrome浏览器下表现为会有
outline
发光效果,IE浏览器下是虚框,同时能够响应
focus
事件。但是,却不能被键盘
focus
。
这种鼠标可以
focus
,但是键盘却不能
focus
的状态,只要
tabindex
属性值为
负值
,因此,
tabindex="-2"
和
tabindex="-1"
没有任何本质区别,既然如此,那就没有必要冒险在玩类似
tabindex="-2"
的新花样,万一哪天浏览器认为这种用法是不合法的呢?在JavaScript中,字符串和数组都有
indexOf
方法,当无法匹配的时候返回的值就是
-1
,对吧,足够了,并没有
-2
之类的返回值,和
tabindex
的路数其实是一致的。
tabIndex=0和tabIndex=1 是1最先被聚焦(focus),
tabindex
属性的键盘索引顺序其实是从数值
1
开始的,不是
0
,
1
索引顺序是最靠前的。也就是说哪怕你在页面的最底部、文档流的最后一个元素设置了
tabindex="1"
,当按下Tab键的时候,首先
focus
就是这最后一个元素。
元素设置
tabindex="-1"
,鼠标和JS可以
focus
,但键盘不能
focus
;
tabindex="0"
和
tabindex="-1"
的唯一区别就是键盘也能
focus
,索引的顺序没有任何的变化。或者你可以这么理解,
<div>
设置了
tabindex="0"
,从键盘访问的角度来讲,相对于
<div>
元素变成了
<button>
元素。
因此,实际上,我们是可以使用
<div>
或者
<span>
元素模拟按钮的,但是千万不能忘记设置
tabindex
属性,如下示意:
<div class="button" tabindex="0" role="button">按钮</div> 既然要用DIV模拟按钮,就应该加这个,让用户无障碍访问 Question1:
tabIndex值被设置为一样的? 此时,focus顺序是根据DOM元素在文档中的位置决定的,越靠前越外层的元素索引顺序更高,也就最后越后被focus 场景一:hover
<div>
显示下拉键盘支持
这是网页中非常常见的一种交互,当我们内容比较静态的时候,常常直接使用CSS
:hover
伪类实现内容的显隐效果,通常,我们都会使用一个大大的
<div>
元素包在外面,从功能上讲,似乎满足了我们的需求,但实际上,对键盘以及其它辅助设备的访问却不友好,因为默认隐藏的下拉内容只能通过鼠标操作显示,键盘永远显示不出来,自然屏幕阅读器等辅助设备也不能读取,此时,就轮到
tabindex
属性来提高我们站点的可访问性了。就是给
<div>
加一个
tabindex="0"
,对吧,小手一抖,体验就有,皆大欢喜,何乐不为!然后再加个
:focus
伪类显示下拉内容就好了!都是举手之劳的事情。
场景二:对网站模块进行自定义的键盘支持
设置
tabindex="-1"
然后使用JS进行
focus
div.setAttribute('tabindex', '-1');
div.focus();
由于设置了
tabindex="-1"
的元素鼠标点击可以
focus
并
outline
轮廓显示,因此,这里的
tabindex="-1"
并不是默认就有,而是按下对应的快捷键后临时动态添加的。
场景三:临时改变页面索引起始位置
当我们点击按钮并显示一个弹框的时候,Tab键的索引起始位置应该是从弹框元素开始的,但是如果我们不做任何处理,索引起始位置还是弹框背后的页面,此时想要通过Tab键一个一个索引到弹框元素,估计天都已经黑了,很显然,为了达到完美的键盘交互体验,我们就需要额外做点事情。 bootstrap中的模态框就采用了这个,加了tabIndex,出现的弹窗,可以用ESC按钮关闭弹窗,友好
-
给弹框
容器
元素设置
tabindex="-1"
; -
弹框显示的时候容器元素
DOM.focus()
使其获取焦点; -
容器元素CSS设置
outline:none
;