如何在 HTML 中创建元素的 Tab 键顺序?

htmlweb developmentfront end technology更新于 2025/4/9 19:24:17

tabindex 是一个全局属性,它使 HTML 元素能够按照键盘的顺序(通常使用键盘的 TAB 键)获得焦点。为了以可访问的方式运行,该属性的值必须为 0、负数或正数。tabindex 属性可以应用于任何 HTML 元素。

语法

<element tabindex = "number">

以下是示例…

示例

在下面的示例中,我们使用了基本 URL = https://www.cainiaomax.com/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://www.cainiaomax.com/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>

输出

On execution ,the output with different links mentioned with names gets displayed. We use tab to navigate between them and we have mentioned different tabindex.

Example: Using Javascript

Now let us see an example of this using 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 会被激活并允许我们进行导航。


相关文章


有用资源