HTML 的 tabindex 属性开发过程当中通常不会使用到,最近开发中有个需求兼顾富交互,便总结了一下。本篇文章同时收录在个人【前端知识点】中,Github连接直达,欢迎 Starhtml
按照惯例,放上官方定义前端
兼容性:Safari不支持!git
在咱们平常使用网页的过程当中,能够经过键盘控制一些元素的聚焦,从而达到便捷访问的目的github
element
分为 focusable
和 非focusable
,若是使用了tabindex就能够改变相关的行为面试
在HTML中有6个元素默认支持聚焦:编程
href
属性的 <a>
标签href
属性的 <link>
标签<button></button>
标签<input />
标签 (排除带有 type="hidden"
属性的)<select></select>
标签<textarea></textarea>
标签以上的元素默认均可以使用 Tab
键,以及 JS focus()
方法聚焦缓存
document.querySelector("a").focus();
tab键
进行聚焦元素时,聚焦的顺序等于元素在代码中的出现前后顺序,当咱们进行富交互优化时,就须要用到 tabindex
这个属性来帮助咱们进行更好用户体验的优化了①元素是否能聚焦:经过键盘这类输入设备,或者经过 JS focus()
方法性能优化
②元素何时能聚焦:在用户经过键盘与页面交互时微信
通俗来讲:就是当用户使用键盘时,tabindex用来定位html元素,即便用tab键时焦点的顺序。网络
tabindex=0,该元素能够用tab键获取焦点
tabindex<=-1,该元素用tab键获取不到焦点,可是能够经过js获取
-1~-999
之间没有区别,但为了可读性和一致性考虑,推荐使用 -1tabindex>=1,该元素能够用tab键获取焦点,并且优先级大于tabindex=0
tabindex>=1
时,数字越小,越先定位到;// HTML <button type="button" tabindex="1">tabindex === 1</button> <button type="button" tabindex="999">tabindex === 999</button> <button type="button" tabindex="0">tabindex === 0</button>
tabindex
数值的节点,根据 DOM节点
前后顺序决定聚焦顺序// HTML <button type="button" tabindex="0">tabindex === 0</button> <button type="button" tabindex="1">tabindex === 1</button> <button type="button" tabindex="999">tabindex === 999</button> <button type="button" tabindex="0">tabindex === 0</button>
tabindex
设置为 -1
时,当前节点使用 tab键
不能聚焦// HTML <button type="button">未设置tabindex</button> <button type="button" tabindex="-1">tabindex === -1</button> <button type="button" tabindex="0">tabindex === 0</button> <button type="button" tabindex="1">tabindex === 1</button>
tabindex
结合JS可让默认不支持聚焦的节点进行聚焦,tabindex
为不超出范围的任何整数值均可以// HTML <button type="button" @click="clickBtn()">点击让DIV聚焦</button> <div id="FocusDiv" ref="FocusDiv" tabindex="-1">这是一个div</div> // JS clickBtn: function() { document.getElementById('FocusDiv').focus(); }
tabindex
为它增长聚焦功能,从而能够像不少可聚焦节点同样进行顺次焦点聚焦了toast
组件、模态框、侧边弹出信息等,咱们不但愿节点被用户聚焦捕获,能够将节点的 tabindex
设置为 -1
,就能避免这一问题tabindex
值的大小来进行处理。若是你以为这篇文章对你有益,烦请点赞以及分享给更多须要的人!
快到碗里来!百度校招还有HC!甩简从来!
极速直接内推【字节跳动】&【百度】&【猿辅导】&【京东】
欢迎关注微信公众号【全栈道路】,获取更多科技相关知识及免费书籍。