如何在 HTML 中建立元素的 Tab 鍵順序?


tabindex 是一個全域性屬性,它使 HTML 元素能夠按順序獲得鍵盤焦點(通常使用鍵盤的 Tab 鍵)。為了以可訪問的方式發揮作用,它需要一個值為 0、負數或正數的值。tabindex 屬性可以應用於任何 HTML 元素。

語法

<element tabindex = "number">

以下是一些示例……

示例

在以下示例中,我們使用基 URL = https://tutorialspoint.tw/index.htm,所有其他相對連結都將以此作為起始 URL。

<!DOCTYPE html> <html> <head> <style> body { text-align:center; } h1 { color:green; } a { text-decoration:none; } </style> </head> <body> <h1>Press TAB To Navigate</h1> <a href="https://tutorialspoint.tw/index.htm" tabindex="2">TUTORIALSPOINT</a> <br> <a href="https://www.youtube.com//" tabindex="1"> YOUTUBE </a> <br> <a href="https://www.google.com//" tabindex="3"> GOOGLE </a> </body> </html>

輸出

執行後,將顯示帶有不同連結和名稱的輸出。我們使用 Tab 鍵在它們之間導航,並且我們提到了不同的 tabindex。

示例:使用 Javascript

現在讓我們看看使用 JavaScript 的示例 -

<!DOCTYPE html> <html> <body> <div tabindex="1">Tutorialspoint</div><br> <div tabindex="3">Google</div><br> <div tabindex="2">Microsoft</div> <script> document.getElementsByTagName('div')[0].focus(); </script> <p tabindex="2"><b>Note:</b>press "tab" to navigate.</p> </body> </html>

輸出

執行上述指令碼後,tabindex 將被啟用,並幫助我們在名稱之間導航。

使用表單操作

在這種情況下,我們建立一個表單並提交值。輸入是在每個指定的文字框中獲取的。這裡,tabindex 用於對錶單中輸入值的順序進行排序。

示例

如以下示例所示,輸入是從按 tabindex = 1、3、4、6 的順序填充的四個文字框中獲取的。

<!Doctype html> <html> <body> <form action="#" method="post"> <table summary="the first column contains the search criteria of the groom, the second column the search criteria of of the bride"> <caption>Search for marriage records</caption> <tr> <th>Search criteria</th> <th>Groom</th> <th>Bride</th> </tr> <tr> <th>First name</th> <td><input type="text" size="30" value="" name="groomfirst" title="First name of the groom" tabindex="1"></td> <td><input type="text" size="30" value="" name="bridefirst" title="First name of the bride" tabindex="4"></td> </tr> <tr> <th>Place of birth</th> <td><input type="text" size="30" value="" name="groombirth" title="Place of birth of the groom" tabindex="3"></td> <td><input type="text" size="30" value="" name="bridebirth" title="Place of birth of the bride" tabindex="6"></td> </tr> </table> </form> </body> </html>

輸出

執行上述程式碼後,我們會得到一個婚姻搜尋記錄表,並且 tabindex 被啟用,允許我們進行導航。

更新於: 2022年9月5日

5K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.