1. 程式人生 > 其它 >vue專案使用tabIndex給dom新增鍵盤事件

vue專案使用tabIndex給dom新增鍵盤事件

在vue專案中,我們通常只能給能獲取焦點的表單元素繫結鍵盤事件,例如給div,img等標籤繫結@keydown.left、@keydown.rigth都是無效的,查了一些資料,發現是要設定屬性tabIndex。

一、tabIndex定義

tabindex 屬性規定當使用 "tab" 鍵進行導航時元素的順序。

在 HTML5 中, tabindex 屬性可用於任何的 HTML 元素。

在 HTML 4.01中, tabindex 屬性可用於: <a>, <area>, <button>, <input>, <object>, <select>, 和 <textarea>

二、tabIndex的使用

tabIndex="-1": 元素可聚焦,但不能通過tab導航到改元素;

tabIndex="0": 元素可聚焦,能通過tab導航到改元素;

tabIndex大於0: 元素可聚焦,可通過tab導航到改元素,數值為tab鍵控制次序。

例如: 在頁面中按tab鍵會先導航到javascript,再導航到html,最後導航到css

 

<div tabindex="2">html</div><br />
<div tabindex="1">javascript</div><br />
<div tabindex="3">css</div>

三、tabIndex樣式

使用tabIndex屬性時,dom元素會被加上一個醜醜的黑框,這是因為自動加上了樣式  :focus-visible {outline: -webkit-focus-ring-color auto 1px;}

解決方案:設定 :focus-visible {outline: 0;}