HTML - tabindex 屬性



HTML tabindex 是一個全域性屬性,允許開發者使 HTML 元素可聚焦,或者透過按 Tab 鍵阻止它們按順序聚焦。

此標籤接受整數值,並根據數字的值返回不同的結果。負值,例如 tabindex = "-1",表示該元素無法透過順序鍵盤導航訪問。正值表示該元素應該在順序鍵盤導航中可聚焦,數字的值決定了元素的順序。

語法

<element tabindex = "" >

應用於

由於 tabindex 是 HTML 中的全域性屬性,因此 HTML 中的所有標籤都支援 tabindex 屬性。

HTML tabindex 屬性示例

下面的示例將說明 HTML tabindex 屬性,以及我們應該在哪裡以及如何使用此屬性!

使用 tabindex 遍歷 div 標籤

在下面的示例中,讓我們看看 tabindex 屬性在 HTML 文件中的用法。此程式碼定義了 tabindex 以遍歷各種標籤,例如 input 和 div。

<!DOCTYPE html>
<html>

<head>
   <style>
      div:focus {
         font-weight: bold;
      }
   </style>
</head>

<body>
   <p>Click anywhere in this output screen 
   and press tab to navigate.</p>
   <label>First in tab order: 
      <input type="text">
   </label>
   <div tabindex="0">
      Tabbable due to tabindex.
   </div>
   <div>
      Not tabbable: no tabindex.
   </div>
   <label>Third in tab order: 
      <input type="text">
   </label>
</body>

</html>

正 tabindex 值

考慮下面的示例,我們演示了 tabindex 屬性的正值。其順序由數字的值定義。也就是說,tabindex="2" 在 tabindex="3" 之前聚焦,在 tabindex="1" 之後聚焦。

<!DOCTYPE html>
<html>

<head>
   <style>
      p:focus {
         font-weight: bold;
      }
   </style>
</head>

<body>
   <h2>Click anywhere in this page, 
      then try pressing tab key.</h2>
   <p tabindex="1">
      First in tab order
   </p>
   <p tabindex="2">
      Second in tab order
   </p>
   <p tabindex="3">
      Third in tab order 
   </p>
</body>

</html>

tabindex 的負值

讓我們看看下面的示例,我們使用 tabindex 屬性的負值。如果我們傳遞負值,則無法透過順序鍵盤導航訪問該元素。

<!DOCTYPE html>
<html>

<head>
   <style>
      div:focus {
         font-weight: bold;
      }
   </style>
</head>

<body>
   <h2>Click anywhere in this page, 
   then try tabbing through the elements.</h2>
   <div tabindex="-1">
      tabindex with -1 value!
   </div>
   <div tabindex="2">
      tabindex with 2 value!
   </div>
   <div tabindex="0">
      tabindex with 0 value!
   </div>
   <div tabindex="-2">
      tabindex with -2 value!
   </div>
</body>

</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
tabindex
html_attributes_reference.htm
廣告
© . All rights reserved.