HTML - DOM 元素 tabIndex 屬性



tabIndex 屬性允許您訪問和更新元素的 tabIndex 屬性的值。tabIndex 屬性控制使用 Tab 鍵遍歷網頁時元素的聚焦順序。

語法

設定 tabIndex 屬性值
element.tabIndex = newValue;
獲取 tabIndex 屬性值
element.tabIndex;

屬性值

描述
newValue 更改元素選項卡順序的整數。

返回值

tabIndex 屬性返回一個整數,該整數儲存元素的選項卡順序。

HTML DOM 元素“tabIndex”屬性示例

以下是一些示例,這些示例展示瞭如何使用“tabIndex”屬性來控制使用 Tab 鍵遍歷網頁時元素的選項卡順序。

使用 tabIndex 屬性控制焦點順序

此示例演示瞭如何使用 tabIndex 屬性。它包括三個<div> 元素,每個元素都有一個 tabIndex 屬性,用於確定它們的選項卡順序。當單擊任何專案時,一個函式會更新<p> 元素以顯示選擇了哪個專案。

<!DOCTYPE html>
<html lang="en">
<head> 
  <style>
    .item {
      padding: 10px;
      margin: 5px;
      border: 1px solid #ccc;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <h1>HTML - DOM Element</h1>
  <h2>tabIndex Property</h2>
  <p>Click on any item or use the Tab key to 
    navigate through the items.<br>Notice the 
    order based on the tabIndex values...
  </p>

  <div class="item"tabindex="1"onclick="select(1)">
  	Item 1
  </div>
  <div class="item"tabindex="2"onclick="select(2)">
  	Item 2
  </div>
  <div class="item"tabindex="3"onclick="select(3)">
  	Item 3
  </div>

  <p id="selitem">Selected item will appear here.</p>

  <script>
    function select(itemId) {
      var s=document.getElementById('selitem');
      s.textContent ='Item'+itemId+'selected!';
    }
  </script>
</body>

</html>

獲取第一個錨元素的選項卡索引

此示例使用 tabIndex 屬性設定網頁上 <a> 元素的選項卡順序。使用者可以透過單擊或使用 Tab 鍵以指定的順序遍歷這些連結。

<!DOCTYPE html>
<html lang="en">
<head>  
  <title>Retrieve Tab Index Example</title>
</head>

<body>
  <h1>HTML - DOM Element</h1>
  <h2>tabIndex Property</h2>
  <p>Use the Tab key to navigate through the links.
    Notice the order based on the tabIndex values.
  </p>

  <a href="https://tutorialspoint.tw/"
    tabindex="3">Tutorialspoint</a><br>
  <a href="http://www.microsoft.com/" 
    tabindex="1">Microsoft</a><br>
  <a href="http://www.google.com/" 
    tabindex="2">Google</a><br>
  <a href="https://www.infosys.com/" 
    tabindex="4">Infosys</a>

  <p id="tabInfo"></p>

  <script>
    // Get the first <a> element
    var fl = document.querySelector('a');

    // Get its tabIndex value
    var tabn = fl.tabIndex;

    // Display the tabIndex value
    var tIi = document.getElementById('tabInfo');
    tIi.textContent = 
    'Tab Index of the first <a> element:'+ tabn;
  </script>
</body>

</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
tabIndex
html_dom_element_reference.htm
廣告