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.